while Loops
A for loop (lessons 78 and 79) knows in advance how many times it will run: once per word in a list, or once per step of a counter. A while loop does not. It keeps repeating as long as a condition stays true, and the condition can depend on anything: a counter, the contents of a file, input typed by a user, or the arrival of a file that another program is still creating. This makes while the right tool for reading input line by line, waiting for something to happen, and processing a list of arguments of unknown length.
Syntax
while CONDITION; do
commands
done
The CONDITION is a command, exactly as it is in an if statement (lesson 66). Before every pass, Bash runs it and looks at its exit status. If the status is 0 (success), the body runs once and the condition is checked again. As soon as the status is non-zero, the loop ends and the script continues after done. The condition is therefore checked before the first pass, and if it fails immediately, the body never runs.
Basic Example
count=1
while [ "$count" -le 3 ]; do
echo "count=$count"
count=$((count + 1))
done
echo "after the loop count=$count"
Output:
count=1
count=2
count=3
after the loop count=4
Understanding the Example
The condition is the test [ "$count" -le 3 ], which is true while count is at most 3. On each pass the body prints the value and then adds 1 with arithmetic expansion (lesson 49). When count reaches 4, the test fails, and the loop ends without printing 4. The final line shows that the variable keeps its last value, as the loop variable of a for loop does.
The body of a while loop must change something that the condition looks at. Here the line count=$((count + 1)) does that. If the update were missing, the condition would stay true forever and the loop would never end (lesson 87).
A while loop and a counting for loop can often do the same work. The difference lies in what controls the repetition: in for (( ... )), the counter is part of the loop header, while in while, the condition and the update are ordinary commands that you place yourself.
Any Command Can Be the Condition
Because the condition is a command, it is not limited to [ ]. The arithmetic form (( )) (lesson 49) makes counters easy to write:
n=3
while (( n > 0 )); do echo -n "$n "; (( n-- )); done; echo "liftoff"
Output:
3 2 1 liftoff
Any program that returns a meaningful exit status works too, and several commands can be combined with && and || (lesson 65). The loop below keeps going while the file still contains the word alpha and fewer than two passes have run:
printf 'alpha\nbeta\n' > words.txt
n=0
while grep -q alpha words.txt && [ "$n" -lt 2 ]; do n=$((n + 1)); done
echo "loop ran $n times (condition is a command list)"
Output:
loop ran 2 times (condition is a command list)
When a condition is a list of several commands, the status of the last one decides whether the loop continues. Placing ! in front of a command reverses its status (lesson 74), which turns the loop into "repeat until this succeeds":
n=0
while ! [ -e done.flag ]; do
n=$((n + 1))
[ "$n" -eq 3 ] && touch done.flag
done
echo "flag appeared after $n passes"
Output:
flag appeared after 3 passes
The loop runs while the file done.flag does not exist. On the third pass the body creates the file, the next check finds it, and the loop stops. The dedicated until loop, covered in lesson 81, expresses this reversed idea without the !.
The Exit Status of a while Loop
A while loop returns the status of the last command that ran in its body. If the body never ran, the status is 0:
x=10
while [ "$x" -lt 5 ]; do echo never; done
echo "status: $?"
i=0
while [ "$i" -lt 3 ]; do i=$((i + 1)); false; done
echo "status after body ending in false: $?"
i=0
while [ "$i" -lt 3 ]; do i=$((i + 1)); done
echo "status after normal end: $?"
Output:
status: 0
status after body ending in false: 1
status after normal end: 0
The failing condition that ends the loop is not what the loop reports. Only the body counts, so the second loop reported the status of its last false.
Reading a File Line by Line
The most common use of while is to read input one line at a time with the read command (lesson 31). The command returns success while it still manages to read a line, and failure at the end of the input, which is exactly the signal a loop needs. The input is attached to the whole loop with a redirection after done (lesson 58):
printf 'first line\n indented line\nthird\\line\n' > data.txt
while read line; do echo "[$line]"; done < data.txt
Output:
[first line]
[indented line]
[thirdline]
This plain form changes the data. It removes the leading spaces of the second line, and it treats the backslash in the third line as an escape character, so the backslash disappeared. The reliable form adds two settings:
while IFS= read -r line; do echo "[$line]"; done < data.txt
Output:
[first line]
[ indented line]
[third\line]
The option -r tells read not to interpret backslashes, and the empty assignment IFS= (written just before read, so it applies only to that command) switches off the trimming of leading and trailing whitespace. Use IFS= read -r whenever the lines must be kept exactly as they are.
A counter in the body numbers the lines, and because the loop is not in a pipeline, the counter is still available afterward:
n=0
while IFS= read -r line; do
n=$((n + 1))
printf '%2d: %s\n' "$n" "$line"
done < data.txt
echo "total lines read: $n"
Output:
1: first line
2: indented line
3: third\line
total lines read: 3
A Last Line Without a Newline
The read command returns failure when it reaches the end of the input before it finds a newline. If the final line of a file has no newline at the end, read still stores the text in the variable, but it reports failure, and the loop stops before the body can use it:
printf 'one\ntwo' > nonl.txt
while IFS= read -r line; do echo "[$line]"; done < nonl.txt
Output:
[one]
The line two was lost. The usual repair is to also run the body when the variable holds text:
while IFS= read -r line || [ -n "$line" ]; do echo "[$line]"; done < nonl.txt
Output:
[one]
[two]
When read fails but $line is not empty, the second part of the condition succeeds, so the final fragment is processed. After that, read fails with an empty variable and the loop ends.
Splitting Each Line into Fields
When read is given several variable names, it splits the line into fields and fills the variables in order. The variable IFS decides where the line is cut. Setting it for just the read command lets a loop process colon-separated data, such as the format of the /etc/passwd file:
cat > users.txt <<'DATA'
ana:1001:/home/ana
bob:1002:/home/bob
chris:1003:/home/chris
DATA
while IFS=: read -r name uid home; do
echo "user=$name uid=$uid home=$home"
done < users.txt
Output:
user=ana uid=1001 home=/home/ana
user=bob uid=1002 home=/home/bob
user=chris uid=1003 home=/home/chris
With the default IFS, the fields are separated by runs of spaces and tabs. This reads a small access log:
printf 'GET /index.html 200 1534\nPOST /login 302 0\n' > access.txt
while read -r method path status size; do
echo "$method request for $path -> $status"
done < access.txt
Output:
GET request for /index.html -> 200
POST request for /login -> 302
If a line has more fields than variables, the last variable receives the entire remainder of the line:
echo "a b c d e" | { read -r first rest; echo "first=[$first] rest=[$rest]"; }
Output:
first=[a] rest=[b c d e]
The braces group the read and the echo so that both run in the same process, which is necessary because the pipe would otherwise lose the variables (see the next section).
Where the Input Comes From
A loop can receive its input from a redirection or from a pipe, and the two behave differently. In a pipeline, each side runs in a subshell (lesson 61), so variables changed inside the loop disappear when it ends:
printf 'a\nb\nc\n' > letters.txt
count=0
cat letters.txt | while read -r l; do count=$((count + 1)); done
echo "count after piped loop: $count"
count=0
while read -r l; do count=$((count + 1)); done < letters.txt
echo "count after redirected loop: $count"
Output:
count after piped loop: 0
count after redirected loop: 3
The piped loop counted correctly inside its own process, but the count of the main script was never changed. Reading from the file with < keeps the loop in the main shell, and the counter survives.
When the data comes from a command rather than a file, process substitution (lesson 151) provides a file-like name for the output, so that the loop can still be fed with < and stay in the main shell:
count=0
while read -r l; do count=$((count + 1)); done < <(cat letters.txt)
echo "count with process substitution: $count"
Output:
count with process substitution: 3
The first < is the ordinary input redirection, and the second <(...) is the process substitution that provides the file name. The two symbols are separated by a space and are not the same operator.
The output of a loop can be piped onward without any problem, because only variables are lost, not text:
i=0
while [ "$i" -lt 3 ]; do echo "row $i"; i=$((i + 1)); done | sort -r
Output:
row 2
row 1
row 0
Infinite Loops with break and continue
A condition that is always true gives a loop that runs until the body decides to leave. The commands true and : both succeed without doing anything, and break leaves the loop:
n=0
while true; do
n=$((n + 1))
[ "$n" -ge 4 ] && break
echo "n=$n"
done
echo "left loop with n=$n"
Output:
n=1
n=2
n=3
left loop with n=4
The same kind of loop written with the colon command, which is the traditional POSIX spelling of "do nothing and succeed" (both true and : are built into the shell, so neither starts another program):
n=0
while :; do
(( ++n > 2 )) && break
echo "colon loop $n"
done
Output:
colon loop 1
colon loop 2
The command continue skips the rest of the current pass and goes back to the condition:
i=0
while [ "$i" -lt 6 ]; do
i=$((i + 1))
(( i % 2 == 0 )) && continue
echo "odd: $i"
done
Output:
odd: 1
odd: 3
odd: 5
The counter is updated before the continue, which is important: if the increment came after it, the even numbers would skip it and the loop would never move past 2. Lesson 84 covers break and continue in detail.
Waiting for Something to Happen
A while loop is the natural way to wait. The condition checks the state, and a short sleep in the body keeps the loop from using the processor at full speed. In this example, a background job creates ready.txt after one second, and the main script waits for it:
cd "$(mktemp -d)"
( sleep 1; touch ready.txt ) &
tries=0
while [ ! -e ready.txt ]; do
tries=$((tries + 1))
echo "waiting (try $tries)"
sleep 0.4
done
echo "ready.txt appeared after $tries tries"
Output:
waiting (try 1)
waiting (try 2)
waiting (try 3)
ready.txt appeared after 3 tries
The number of tries depends on timing and can differ from run to run. A real script should also have a limit, so that it gives up instead of waiting forever if the file never appears. The condition can combine both ideas with &&, as shown earlier with the command list. Lesson 142 introduces the timeout command for a stricter approach.
Processing Arguments with shift
A script does not know how many arguments it will receive. The test [ $# -gt 0 ] checks whether any are left, and the shift command (lesson 44) discards the first one so that the next moves into $1:
#!/usr/bin/env bash
while [ $# -gt 0 ]; do
echo "argument: $1 ($# left)"
shift
done
echo "no arguments left"
Running bash args.sh one "two words" three printed:
argument: one (3 left)
argument: two words (2 left)
argument: three (1 left)
no arguments left
Each pass handles the first argument and then shifts the list down by one. The loop ends when $# reaches 0. This pattern is the foundation of hand-written option parsers, where the body uses a case statement (lessons 75 and 76) to decide what each argument means, and shifts twice for options that take a value. Lessons 127 and 130 build on it.
A Prompt Loop
Combining while true, read and case gives a loop that keeps asking until the user chooses to stop. The || break after read ends the loop when the input is closed, for example when a pipe ends, so that the script cannot spin forever:
#!/usr/bin/env bash
while true; do
read -r -p "Enter a number (q to quit): " answer || break
case "$answer" in
q|Q) echo "bye"; break ;;
""|*[!0-9]*) echo "not a number: $answer" ;;
*) echo "square of $answer is $(( answer * answer ))" ;;
esac
done
echo "loop finished"
Running printf '7\nabc\n12\nq\n' | bash prompt.sh printed:
square of 7 is 49
not a number: abc
square of 12 is 144
bye
loop finished
The prompt text of read -p is shown only when the input is a terminal, which is why it does not appear in this piped run. At a keyboard, each answer would follow the prompt. The pattern ""|*[!0-9]* catches an empty answer and any answer that contains a character other than a digit, so only strings made of digits reach the arithmetic. If the input ends without q, for example after the single line 5, the read fails, break runs, and the loop finishes with loop finished. Menus (lessons 86 and 134) are built on the same structure.
Portability
The while ... do ... done structure, the read command, and shift all work in every POSIX shell, including Dash:
#!/bin/sh
i=1
while [ "$i" -le 3 ]; do
echo "i=$i"
i=$((i + 1))
done
This prints i=1, i=2 and i=3 in Dash, and a while IFS=' ' read -r x y loop over a file works there as well. Two Bash features from this lesson do not carry over. The arithmetic condition (( n > 0 )) is read by Dash as two nested subshells, which ends in an error such as n: not found. Process substitution is rejected with Syntax error: redirection unexpected. A script for sh should use [ "$n" -gt 0 ] and read from a file or a here document instead.