1

I have a bash function on one of our test servers that deploys our code, but one of the commands fails frequently and we can't find the cause. We just retry until it works.

I want to have the function retry if that command fails. In the function, I did something like this:

command_to_run || { echo "failed, retrying"; call_function; }

Which calls the function again like I would want, but it also allows the function to continue execution. How do I stop the execution of the current function before calling it again?

3 Answers 3

8

Here's an even simpler variant of @terdon's suggestion:

while ! command_to_run; do
    echo "failed, retrying"
    sleep 1
done

while actually takes a command, so it can test the success/failure of command_to_run directly rather than having to deal with $?. Normally, while runs the loop as long as the command succeeds; in this case, I use ! to negate that and run the loop as long as the command fails (i.e. until it succeeds).

2
  • +1 This is the better answer.
    – chepner
    Mar 21, 2013 at 22:39
  • Indeed it is, +1.
    – terdon
    Mar 22, 2013 at 2:19
4

Try a while loop:

er=1; while [[ $er != 0 ]]; do command_to_run; er=$?; sleep 1; done

Bash saves the exit status of the last command in the special variable $?. The loop above saves the exit status of command_to_run as $er and then reruns the command until an exit status of 0 (exited correctly) is returned. It will wait one second between runs as suggested by Flup in the comments below.

3
  • might want to put a sleep in there to avoid a tight loop.
    – Flup
    Mar 21, 2013 at 16:24
  • @Flup good point, done.
    – terdon
    Mar 21, 2013 at 16:26
  • The sleep won't be necessary as the command is a long running one. This worked like a charm though, thanks! Mar 21, 2013 at 16:57
0

I find until is more readable in this case.

until command_to_run; do
    echo "failed, retrying"
    sleep 1
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .