Bash by Example: Until Loop
Executing a loop repeatedly until a condition becomes true, understanding the inverse logic compared to while loops, implementing countdown and build-up patterns, and choosing between until and while based on natural condition expression.
Code
#!/bin/bash
count=1
# Run UNTIL count is greater than 3
until [ $count -gt 3 ]; do
echo "Count: $count"
((count++))
done
# Waiting for a resource (simulated)
echo -e "\nWaiting for file..."
# In real usage: until [ -f "lock.file" ]; do ...
until [ $count -gt 5 ]; do
echo -n "."
sleep 0.5
((count++))
done
echo " Done!"Explanation
The until loop is the semantic opposite of the while loop. It executes the block of code as long as the test command returns a non-zero exit status (failure). In other words, it runs until the condition becomes true.
This is particularly useful for waiting logic. For example, waiting until a file exists, until a host is pingable, or until a service starts. Instead of writing while [ ! condition ], you can write until [ condition ], which often reads more naturally.
Like other loops, you must ensure the condition eventually becomes true, or the loop will run indefinitely. Always include a mechanism to update the state or a timeout to prevent infinite hanging.
Code Breakdown
$count -gt 3 is FALSE. Once count becomes 4, the condition is true, and the loop terminates.
