until Loops
An until loop repeats a block of commands until a condition becomes true. It is the mirror image of the while loop from lesson 80: a while loop keeps going as long as its condition succeeds, while an until loop keeps going as long as its condition fails. The moment the condition succeeds, the loop stops.
Both loops can express the same logic. The difference is readability. Some conditions are naturally phrased as "keep going while X is true" (while there are lines left), and others as "keep going until X happens" (until the file appears, until the server answers, until the counter reaches 10). Choosing the form that matches how you would say it aloud makes a script easier to read.
Syntax
until CONDITION; do
commands
done
The CONDITION is an ordinary command, exactly as in an if statement (lesson 66). Before every pass, Bash runs it and looks at its exit status:
- If the status is non-zero (failure), the body runs once, and then the condition is checked again.
- If the status is 0 (success), the loop ends and the script continues after
done.
Compare this with while, where the meaning of the two outcomes is swapped: while continues on status 0, until continues on a non-zero status. Like while, the condition is checked before the first pass, so the body can run zero times.
Basic Example
count=1
until [ "$count" -gt 3 ]; do
echo "count=$count"
count=$((count + 1))
done
echo "after: count=$count"
Output:
count=1
count=2
count=3
after: count=4
Understanding the Example
The condition is the test [ "$count" -gt 3 ] (lesson 73), which is true when count is greater than 3. Because this is an until loop, the body runs while that test is false:
countis 1. The test fails, so the body runs and printscount=1, then adds 1.countis 2. The test fails again, so the body printscount=2.countis 3. The test still fails, so the body printscount=3.countis 4. The test succeeds, so the loop ends without printing 4.
The last line shows that count keeps its final value (4) after the loop, just like an ordinary variable. The body also updates count itself with arithmetic expansion (lesson 49). A loop body must change something the condition looks at, or the condition never changes and the loop never ends (lesson 87 covers this in detail).
Checked Before the First Pass
If the condition is already true at the start, the body never runs:
x=10
until [ "$x" -gt 5 ]; do echo never; done
echo "status: $?"
Output:
status: 0
Nothing was printed because 10 -gt 5 is true immediately. The status of a loop whose body never ran is 0. An until loop is therefore not a "do this at least once" loop. Bash has no do ... until form like some other languages; the condition always comes first.
Choosing Between until and while
The two loops are connected by negation. Any until loop can be rewritten as a while loop by reversing the condition with ! (lesson 74), and the other way around:
# until: keep going until the flag file exists
n=0
until [ -e done.flag ]; do
n=$((n + 1))
[ "$n" -eq 3 ] && touch done.flag
done
echo "flag appeared after $n passes"
# while: the same loop with the condition reversed
n=0
while ! [ -e done2.flag ]; do
n=$((n + 1))
[ "$n" -eq 3 ] && touch done2.flag
done
echo "while ! version: $n passes"
Output:
flag appeared after 3 passes
while ! version: 3 passes
Both loops behave identically. In the until version the condition reads naturally ("until the flag file exists"), while the while ! version requires the reader to mentally flip the meaning. That is the main reason until exists: it removes the !.
A useful rule of thumb is to look at the condition. If you would write a ! in front of it for a while loop, an until loop is usually clearer. If the condition is already positive (while [ "$i" -lt 10 ]), keep while.
Counting Down and Up
For counters, until works with both the test command and the arithmetic command (( )):
n=3
until (( n == 0 )); do echo -n "$n "; (( n-- )); done; echo liftoff
Output:
3 2 1 liftoff
The condition (( n == 0 )) succeeds when n equals 0. The body prints the value and decrements it. Because the loop ends the moment n is 0, the 0 itself is never printed. The (( n-- )) form is a Bash feature (see the portability section below); n=$((n - 1)) works everywhere.
Any Command Can Be the Condition
The condition is not limited to [ ]. Any command whose exit status carries a yes/no meaning works, including grep -q, ping, curl, test and your own functions. A common use is waiting for a message to appear in a log file. In this example, a background job appends the word READY to the file after one second, and the main script polls the file until it sees it:
printf 'one\ntwo\n' > log.txt
( sleep 1; echo "READY" >> log.txt ) &
tries=0
until grep -q READY log.txt; do
tries=$((tries + 1))
sleep 0.4
done
echo "found READY after $tries checks"
Output (the number of checks depends on timing):
found READY after 3 checks
The grep -q command prints nothing and returns 0 when it finds a match and 1 when it does not (lesson 21). The loop therefore keeps running while the word is missing and stops as soon as it appears. The short sleep between checks stops the loop from using the processor at full speed. The ( ... ) & part starts a background job (lesson 136); here it only simulates another program that is slow to finish.
A function can also serve as the condition, which is a clean way to give a complicated test a name:
tries=0
check() { tries=$((tries + 1)); [ "$tries" -ge 3 ]; }
until check; do echo "not yet ($tries)"; done
echo "check passed on try $tries"
Output:
not yet (1)
not yet (2)
check passed on try 3
The function's status is the status of its last command, the test. It fails twice and succeeds on the third call, which ends the loop. Notice that the condition itself has a side effect (it increments tries). This works, but keep such conditions short so that the loop remains easy to follow.
A Condition Made of Several Commands
The condition can be a list of commands. As in a while loop, the status of the last command in the list decides whether the loop continues:
a=0
until a=$((a+1)); [ "$a" -ge 3 ]; do echo "a=$a"; done
echo "final a=$a"
Output:
a=1
a=2
final a=3
Before each pass, Bash runs a=$((a+1)) and then the test. The assignment always succeeds, so only the test controls the loop. The update therefore happens inside the condition, and the body does not need one. This style is compact, but it hides the update, so it is usually clearer to put the counter change in the body.
Combining Conditions with || and &&
A very common real-world pattern is a bounded retry: keep trying until something works, but give up after a fixed number of attempts. With until, the condition says "stop when the work is done or when we have used all our attempts":
attempts=0
max=5
until [ -e ok.flag ] || [ "$attempts" -ge "$max" ]; do
attempts=$((attempts + 1))
echo "attempt $attempts"
[ "$attempts" -eq 3 ] && touch ok.flag
done
if [ -e ok.flag ]; then echo "succeeded after $attempts attempts"; else echo "gave up"; fi
Output:
attempt 1
attempt 2
attempt 3
succeeded after 3 attempts
Here the file ok.flag stands for any successful result, and the line that creates it on the third attempt only simulates real work succeeding. The loop ends because the first part of the condition became true. If the file never appeared, the second part would end the loop after five attempts, and the final if would print gave up:
attempts=0
until [ "$attempts" -ge 3 ] || [ -e never.flag ]; do
attempts=$((attempts + 1))
echo "attempt $attempts"
done
[ -e never.flag ] || echo "gave up after $attempts attempts"
Output:
attempt 1
attempt 2
attempt 3
gave up after 3 attempts
The || operator (lesson 65) makes the condition succeed if either side succeeds. Always add an upper limit like this to any loop that waits for something outside the script's control. Without it, a missing file or an unreachable server makes the script wait forever. Lesson 142 shows the timeout command as another way to set a limit.
The Exit Status of an until Loop
An until loop returns the exit status of the last command that ran in its body, or 0 if the body never ran. The condition that finally ends the loop does not count:
i=0
until [ "$i" -ge 3 ]; do i=$((i + 1)); false; done
echo "status after body ending in false: $?"
i=0
until [ "$i" -ge 3 ]; do i=$((i + 1)); done
echo "status after normal end: $?"
y=9
until [ "$y" -gt 1 ]; do :; done
echo "status when body never ran: $?"
Output:
status after body ending in false: 1
status after normal end: 0
status when body never ran: 0
In the first loop the last body command was false, so the loop returned 1. This matters when a loop is the last command of a function or script, or when you test its status with if (lesson 66).
Reading Input Until a Condition Is Met
An until loop works well for asking a question until the user gives an acceptable answer. The important detail is what happens when the input runs out. Here is a loop that asks until it receives yes, and handles the end of the input explicitly:
answer=""
until [ "$answer" = yes ]; do
read -r answer || { echo "input ended"; break; }
echo "you typed: $answer"
done
Feeding it printf 'no\nmaybe\nyes\nextra\n' prints:
you typed: no
you typed: maybe
you typed: yes
Feeding it only printf 'no\nmaybe\n' prints:
you typed: no
you typed: maybe
input ended
The read command (lesson 31) fails at the end of the input. The || { ...; break; } part catches that failure and leaves the loop with break (lesson 84). Without it, read would keep failing, the answer variable would keep its last value, and the loop would run forever.
A related trap appears when read is placed inside the condition itself:
printf 'a\nb\n' > in.txt
cnt=0
until IFS= read -r line && [ "$line" = quit ]; do
cnt=$((cnt+1))
echo "body $cnt: [$line]"
[ "$cnt" -ge 5 ] && { echo "stopped by safety limit"; break; }
done < in.txt
Output:
body 1: [a]
body 2: [b]
body 3: []
body 4: []
body 5: []
stopped by safety limit
The file has no line quit, so after the second line read fails, which makes the condition fail, and an until loop continues when its condition fails. The loop would run forever on an empty variable if the safety limit were not there. For reading lines until the end of input, use while read (lesson 80). Use until for reading only when the stopping condition is a value you check yourself.
Processing Arguments with shift
The test [ $# -eq 0 ] is true when no arguments are left, so an until loop can walk through the positional parameters with shift (lesson 44):
set -- a b c
until [ $# -eq 0 ]; do echo "arg $1"; shift; done
Output:
arg a
arg b
arg c
The loop runs until no arguments remain. The same loop with while [ $# -gt 0 ] is just as common; the choice is a matter of reading preference.
Infinite Loops with until
A condition that never succeeds gives a loop that runs until the body leaves it. The command false always fails, so until false is the mirror of while true:
n=0
until false; do
n=$((n+1))
[ "$n" -ge 3 ] && break
done
echo "left with n=$n"
Output:
left with n=3
This form is legal, but most scripts write while true for an intentional infinite loop, because "while true" is easier to read than "until false". Lesson 87 covers how to write such loops safely.
Portability
The until ... do ... done structure, the test command [ ], and arithmetic expansion $(( )) work in every POSIX shell, including Dash:
#!/bin/sh
i=1
until [ "$i" -gt 3 ]; do
echo "i=$i"
i=$((i + 1))
done
Running this with Dash prints i=1, i=2 and i=3. The arithmetic command (( )) used in the countdown earlier is a Bash feature and is not available in Dash, so scripts meant for sh should use [ "$n" -eq 0 ] and n=$((n - 1)) instead (see lessons 188 and 189).