Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 7 down vote accepted

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

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

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).

share|improve this answer
+1 This is the better answer. – chepner Mar 21 '13 at 22:39
Indeed it is, +1. – terdon Mar 22 '13 at 2:19

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.

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

I find until is more readable in this case.

until command_to_run; do
    echo "failed, retrying"
    sleep 1
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.