How to retry a bash command until its status is ok or until a timeout is reached?
My best shot (I'm looking for something simpler):
NEXT_WAIT_TIME=0 COMMAND_STATUS=1 until [ $COMMAND_STATUS -eq 0 || $NEXT_WAIT_TIME -eq 4 ]; do command COMMAND_STATUS=$? sleep $NEXT_WAIT_TIME let NEXT_WAIT_TIME=NEXT_WAIT_TIME+1 done
The timeout command stops an executed process after the timeout period: $ timeout 1s bash -c 'for((;;)); do :; done' $ echo $? 124. Here, we run an endless loop. We set a timeout of one second before timeout should kill the process. Importantly, note the exit code.
Using break Inside for Loops To add a conditional statement and exit a for loop early, use a break statement. The following code shows an example of using a break within a for loop: #!/bin/bash for i in {1.. 10} do if [[ $i == '2' ]] then echo "Number $i!" break fi echo "$i" done echo "Done!"
$0 bash parameter is used to reference the name of the shell or shell script. so you can use this if you want to print the name of shell script. $- $- (dollar hyphen) bash parameter is used to get current option flags specified during the invocation, by the set built-in command or set by the bash shell itself.
How to Use the Bash Sleep Command. Sleep is a very versatile command with a very simple syntax. It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.
You can simplify things a bit by putting command
right in the test and doing increments a bit differently. Otherwise the script looks fine:
NEXT_WAIT_TIME=0 until [ $NEXT_WAIT_TIME -eq 5 ] || command; do sleep $(( NEXT_WAIT_TIME++ )) done [ $NEXT_WAIT_TIME -lt 5 ]
One line and shortest, and maybe the best approach:
timeout 12h bash -c 'until ssh root@mynewvm; do sleep 10; done'
Credited by http://jeromebelleman.gitlab.io/posts/devops/until/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With