Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retry a Bash command with timeout

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 
like image 974
Philippe Blayo Avatar asked Sep 07 '12 15:09

Philippe Blayo


People also ask

What is bash timeout?

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.

How do you break out of a for loop in bash?

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!"

What does \$ mean in bash?

$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 do I sleep in a bash script?

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.


2 Answers

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 ] 
like image 73
Grisha Levit Avatar answered Sep 22 '22 20:09

Grisha Levit


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/

like image 22
petertc Avatar answered Sep 23 '22 20:09

petertc