How to Use Until Loop in Bash: Syntax and Examples
In bash, an
until loop runs commands repeatedly until a specified condition becomes true. It checks the condition before each iteration and continues looping while the condition is false.Syntax
The until loop syntax in bash is:
until CONDITION; do- Starts the loop and checks the condition.COMMANDS- Commands to run while the condition is false.done- Ends the loop.
The loop runs as long as the CONDITION returns false (exit status not zero). When the condition becomes true (exit status zero), the loop stops.
bash
until [ CONDITION ] do COMMANDS done
Example
This example counts from 1 to 5 using an until loop. It prints the number each time and stops when the number is greater than 5.
bash
count=1 until [ $count -gt 5 ] do echo "Count is $count" ((count++)) done
Output
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Common Pitfalls
Common mistakes when using until loops include:
- Using the wrong condition logic (remember
untilloops run while the condition is false). - Forgetting to update variables inside the loop, causing infinite loops.
- Using incorrect test syntax inside
[ ]or missing spaces.
Example of a wrong and right way:
bash
# Wrong: condition logic reversed, causes infinite loop count=1 until [ $count -lt 5 ] do echo $count ((count++)) done # Right: condition checks when count is greater than 5 count=1 until [ $count -gt 5 ] do echo $count ((count++)) done
Output
1
2
3
4
5
Quick Reference
- until CONDITION; do ... done: Loop runs while CONDITION is false.
- Use
[ ]or[[ ]]for conditions. - Update variables inside the loop to avoid infinite loops.
- Use
breakto exit loop early if needed.
Key Takeaways
The until loop runs commands repeatedly while the condition is false.
Always update variables inside the loop to prevent infinite loops.
Use correct test syntax with spaces inside [ ] or [[ ]].
The loop stops when the condition becomes true (exit status zero).
Use break to exit the loop early if needed.