while Loops and Reading Files
Prerequisites: for loops, Reading input
A while loop repeats as long as its condition succeeds.
count=1
while (( count <= 3 )); do
echo "Count: $count"
(( count++ ))
done
Count: 1
Count: 2
Count: 3
until is the opposite: it loops until the condition succeeds.
Reading a file line by line
The most important while pattern in Bash:
printf '%s\n' "Ada,London" "Linus,Helsinki" "Grace,New York" > people.csv
while IFS=, read -r name city; do
echo "$name lives in $city"
done < people.csv
Ada lives in London
Linus lives in Helsinki
Grace lives in New York
< people.csvat the end feeds the file into the loop.read -rreads one line per pass; the loop ends at the end of the file.IFS=,splits each line on commas intonameandcity. (UseIFS=alone to keep each whole line exactly as it is.)
Processing command output
Pipe a command's output into while read:
printf '%s\n' 3 9 4 > numbers.txt
total=0
while read -r n; do
(( total += n ))
done < numbers.txt
echo "Total: $total"
Total: 16
Retrying something
# illustrative
attempt=1
until curl -fs https://example.com > /dev/null; do
if (( attempt >= 5 )); then
echo "Giving up after $attempt attempts" >&2
exit 1
fi
echo "Attempt $attempt failed, retrying in 2s..."
(( attempt++ ))
sleep 2
done
echo "Site is up"
Common mistakes
cat file | while read ...runs the loop in a subshell, so variables changed inside (liketotal) are lost afterwards. Redirect withdone < fileinstead.- Forgetting
-r, so backslashes in the data disappear. - A missing last newline in the file makes
readskip the final line;while IFS= read -r line || [[ -n $line ]]handles it.