Avoiding Infinite Loops
An infinite loop is a loop whose condition never becomes false (for while) or never becomes true (for until), so the loop never ends by itself. In a script this usually looks like a program that hangs: the terminal prints the same line again and again, or prints nothing while one CPU core runs at full speed.
Some infinite loops are written on purpose, such as a service that waits for work forever, and they always contain a planned way out. The ones to avoid are the accidental ones. This lesson shows the typical causes, how to recognize them, how to stop a running loop and how to write loops that cannot get stuck.
How a Loop Gets Stuck
A while loop (lesson 80) runs the body as long as the condition command succeeds. If nothing in the body changes what the condition tests, the result is the same on every pass, and the loop continues forever. Every accidental infinite loop is one of a few patterns.
The counter is never updated
i=1
while [ "$i" -le 3 ]; do
echo "i is $i"
done
The condition tests i, but the body never changes i. The output would never stop:
i is 1
i is 1
i is 1
i is 1
i is 1
...
To show it safely here, the loop was cut with | head -n 5. After five lines head exits, and the loop is stopped by a signal when it writes to the closed pipe (the pipeline status was 141 0, where 141 is 128 plus the signal number 13). The fix is to add i=$((i + 1)) inside the loop (lesson 49).
The step skips the target value
n=0
while [ "$n" -ne 10 ]; do
n=$((n + 3))
done
The values of n are 3, 6, 9, 12, 15, 18, and so on. The loop waits for the value 10, but n jumps over it, so n -ne 10 stays true forever. In a test with a safety limit, n had reached 18 after six passes and the loop had not ended.
The cure is to compare with a range test instead of an exact value:
n=0
while [ "$n" -lt 10 ]; do
n=$((n + 3))
done
echo "n=$n"
n=12
The same problem hits until. This loop counts down by 2 from an odd number and never meets 0:
n=5
until [ "$n" -eq 0 ]; do
n=$((n - 2))
done
The values are 3, 1, -1, -3, and so on. After five passes, a test with a limit showed n=-5. Writing the condition as until [ "$n" -le 0 ] ends the loop (n=-1 at the end), because -le accepts every value at or below zero.
continue skips the update
A continue (lesson 84) that runs before the counter update sends the loop back to the condition with the same value:
i=0
while [ "$i" -lt 5 ]; do
if [ "$i" -eq 2 ]; then
continue
fi
echo "i=$i"
i=$((i + 1))
done
The loop prints i=0 and i=1, and then it sticks at i=2 forever, because the continue jumps back to the condition before the update line is reached. A test with a guard counter confirmed this and had to stop the loop by itself. The fix is to update the counter first, before any continue:
i=0
while [ "$i" -lt 5 ]; do
i=$((i + 1))
[ "$i" -eq 3 ] && continue
echo "i=$i"
done
i=1
i=2
i=4
i=5
A state that never changes
status=running
while [ "$status" != "done" ]; do
:
done
Here the loop waits for a variable to change, but nothing in the shell changes it. A variable only changes when the loop (or something it calls) assigns to it. If you are waiting for something outside the script, such as a file or a service, the loop must check that outside thing on each pass, for example with [ -e file ] or a command such as curl, instead of reading a variable that stays the same.
Reading input that has ended
This loop looks harmless:
while true; do
read -r line
echo "got [$line]"
done < in.txt
When in.txt holds the lines a and b, the loop prints them, and then it continues forever. At the end of the file read fails, but nobody looks at its status, so the loop goes on with an empty line. A version with a guard counter printed
got [a]
got [b]
got []
got []
got []
stopped by guard
The fix is to leave the loop when read fails:
while true; do
read -r line || break
echo "got [$line]"
done < in.txt
or, simpler, to let read be the condition:
while read -r line; do
echo "got [$line]"
done < in.txt
Both versions print got [a] and got [b] and then stop. The second form is the standard way to read a file line by line (lessons 80 and 114).
Spotting a Stuck Loop with set -x
When a loop hangs and the reason is not clear, turn on tracing for the loop. set -x makes Bash print every command, with the values of the variables already expanded (lesson 126 covers it in detail):
i=1
guard=0
set -x
while [ "$i" -le 3 ]; do
guard=$((guard + 1))
[ "$guard" -ge 3 ] && break
done
set +x
+ '[' 1 -le 3 ']'
+ guard=1
+ '[' 1 -ge 3 ']'
+ '[' 1 -le 3 ']'
+ guard=2
+ '[' 2 -ge 3 ']'
+ '[' 1 -le 3 ']'
+ guard=3
+ '[' 3 -ge 3 ']'
+ break
+ set +x
Every condition check shows 1 -le 3. The value of i never changes, so the trace makes the cause visible within a few lines. The guard counter in this example only exists to stop the demonstration after three passes.
Stopping a Loop That Is Already Running
Ctrl + C
In an interactive terminal, Ctrl + C sends the interrupt signal (SIGINT) to the running script, and the script ends. The shell then shows the prompt again. A script that was stopped this way normally returns a status of 130 (128 plus the signal number 2).
The kill command
If the script runs in the background or in another terminal, find its process ID and send it a signal (lessons 139 and 140):
bash stuck.sh &
pid=$!
kill "$pid"
wait "$pid"
echo "status after kill: $?"
status after kill: 143
The default signal of kill is SIGTERM, number 15, so the status is 128 + 15 = 143. If a program ignores SIGTERM, kill -9 "$pid" (SIGKILL) ends it without giving it a chance to clean up, so use it only as a last step.
Cleaning up when a loop is stopped
A loop that creates temporary files or lock files should remove them when it is interrupted. The trap command (lesson 123) runs a command when the script receives a signal:
trap 'echo "terminated, cleaning up"; exit 143' TERM
while true; do sleep 0.1; done
Started in the background and ended with kill, the script printed
terminated, cleaning up
status: 143
The trap command runs first, then the script exits with the status it was told to use. The same works for INT, the signal behind Ctrl + C. (A background job started with & in a non-interactive shell ignores SIGINT, so this example uses TERM, which can be tested from a script.) Lesson 141 explains interrupt handling in more detail.
Writing Loops That Always End
The best protection is to build a limit into every loop that waits for something outside your control.
A maximum number of attempts
max=5
attempt=0
until [ -e ready.flag ]; do
attempt=$((attempt + 1))
if [ "$attempt" -ge "$max" ]; then
echo "giving up after $attempt checks"
break
fi
done
giving up after 5 checks
When ready.flag never appears, the loop makes five checks and then leaves. The break is in the body, so the loop ends in one of two ways: the condition becomes true, or the attempt limit is reached. After the loop, test [ -e ready.flag ] once more if the script must know which of the two happened.
The same limit can be placed in the condition, which keeps all the rules in one place:
tries=0
until [ -e never.flag ] || [ "$tries" -ge 3 ]; do
tries=$((tries + 1))
echo "try $tries"
sleep 0.1
done
[ -e never.flag ] || echo "never.flag still missing after $tries tries"
try 1
try 2
try 3
never.flag still missing after 3 tries
The sleep between the checks matters. A loop that checks a file thousands of times per second wastes CPU time, while a short pause gives the other program time to do its work.
A time limit with SECONDS
Bash keeps a variable called SECONDS that counts the seconds since the shell started. It lets you set a deadline instead of counting attempts:
( sleep 1; touch ready.flag ) &
deadline=$((SECONDS + 5))
while [ ! -e ready.flag ]; do
if [ "$SECONDS" -ge "$deadline" ]; then
echo "timed out"
break
fi
sleep 0.2
done
[ -e ready.flag ] && echo "ready file appeared"
wait
ready file appeared
The background subshell creates the file after one second, so the loop ends well before the five-second deadline. When the file never appears, the loop prints timed out and leaves. A second test, with a 2-second limit and no file, printed timed out after 2s. SECONDS is a Bash feature; a portable script can use date +%s instead (lessons 188 and 189).
The timeout command
If you cannot change the script that gets stuck, run it under timeout (lesson 142), which ends a command after a number of seconds:
timeout 1 bash stuck.sh
echo "timeout status $?"
timeout status 124
The status 124 means that the time limit was reached and timeout stopped the command. This protects a scheduled script that might otherwise run for days.
Infinite Loops Written on Purpose
A long-running script, such as a watcher or a small server, is a loop that should not end by its condition. Bash gives several equivalent ways to write it:
while true; do ...; done
while :; do ...; done
for (( ; ; )); do ...; done
true and : are both commands that always succeed (lesson 80). The C-style form with three empty parts (lesson 79) has no condition at all, which means "always continue". In each case, a normal exit must be planned with break, return or exit:
n=0
while true; do
n=$((n + 1))
[ "$n" -ge 3 ] && break
done
echo "while true ended at n=$n"
while true ended at n=3
The other two forms ended at n=2 (while :) and n=4 (for (( ; ; ))) with the same kind of break. A deliberate infinite loop should also contain a sleep or a blocking command such as read, so that it does not use a whole CPU core while it waits.
Portability
The while, until, break and [ ] constructs shown here work in any POSIX shell. A Dash test confirmed that while :, until [ "$i" -ge 3 ] and $(( )) give the expected results. The C-style for (( ; ; )) form does not exist in Dash and fails with
d87.sh: 7: Syntax error: Bad for loop variable
Use while : in scripts that must run under sh. SECONDS, sleep 0.2 with a fractional value and timeout are not guaranteed everywhere: SECONDS is a Bash feature, and a fractional sleep works with GNU coreutils but not with every sleep program.