In case we want to automate a task that might not work immediately but is expected to eventually succeed it can be necessary to recourse to a command in a loop. This can be done easily with while or until loops.
While Loop executes the command when the condition is true and keeps executing it until the condition becomes false. When the condition becomes false, the loop exits.
Example :
while ! mount /mnt/shared; do
echo "Mount failed. Retrying in 10 seconds..."
sleep 10
done
echo "Mount succeeded!"
In this example we mount a network filesystem (e.g., NFS or SMB) which might not be available immediately after boot or on network delay.
while ! mount /mnt/shared;
is the conditional statement : while NOT (!) able to mount
do
echo "Mount failed. Retrying in 10 seconds..."
sleep 10
done
So if the condition is true (i.e if /mnt/shared not mounted), the block of code enclosed in do...done is executed. Once the condition becomes false ( the mount is done) "mount succeeded" is displayed.
Until Loop executes the command when the condition is false and keep executing it until the condition becomes true. when the condition becomes true, the loop exits. It is the opposite of while loop, but will gives us same results.
Example :
until [ -f /tmp/myfile.txt ]; do
echo "Waiting for file to be created..."
sleep 3
done
Use case: Another process is expected to create the file, for example a service creates a .lock or .ready file when it finishes and our script waits for that signal file before proceeding.
[ -f /tmp/myfile.txt ]
source : 1