Do until script succeeds in bash

Posted: 12th September 2013 by Tim in Bash, Linux
Tags: , , , , , ,

Occasionally you want to continue retrying a script or program until it succeeds. In bash, this can be done using the until ... do ... done syntax, like so:

until (<command>); do echo "FAIL!"; sleep 10; done

For example, if you wanted to halt processing until a program.log file was created, you could do something like this:

until (ls program.log >/dev/null 2>&1); do echo 'Log not ready yet. Will try again in 5 seconds.'; sleep 5; done; echo 'Ready!';

Or, on multiple lines:

until (ls program.log >/dev/null 2>&1);
do
    echo 'Log not ready yet. Will try again in 5 seconds.';
    sleep 5;
done;
echo 'Ready!';

(There are much better ways to check if a file exists in bash. I’ve used this method here to show how to use until in this way)

This script will print something like:

Log not ready yet. Will try again in 5 seconds.
Log not ready yet. Will try again in 5 seconds.
Ready!