Bash Loops
Loops repeat commands: once for each file, each line of a file, each number in a range, or until a condition changes. Bash has for, while and until loops, plus break and continue to control them.
for over a list
for fruit in apple banana cherry; do
echo "I like $fruit"
done
for file in report.txt "my notes.txt"; do
echo "processing: $file"
doneI like apple
I like banana
I like cherry
processing: report.txt
processing: my notes.txt
The list can be words, quoted strings, variables, an array ("${arr[@]}"), a glob (*.log) or a brace expansion ({1..5}).
Ranges and C-style loops
for i in {1..5}; do printf '%s ' "$i"; done; echo
for i in {10..0..5}; do printf '%s ' "$i"; done; echo
for (( i = 1; i <= 16; i *= 2 )); do printf '%s ' "$i"; done; echo
n=4
for i in $(seq 1 "$n"); do printf 'n%s ' "$i"; done; echo1 2 3 4 5
10 5 0
1 2 4 8 16
n1 n2 n3 n4
Brace ranges {1..5} can't contain variables ({1..$n} doesn't work), because braces are expanded before variables. Use seq or the C-style for (( ; ; )) when the limits are variables.
Looping over files
Use a glob, never the output of ls. Add a guard for the case that nothing matches, because then the pattern itself is left in the list:
mkdir logs
printf 'a\nb\n' > logs/app.log
printf 'c\n' > logs/db.log
for f in logs/*.log; do
echo "$f has $(wc -l < "$f") lines"
done
for f in logs/*.csv; do
[ -e "$f" ] || { echo "no CSV files (the loop saw: $f)"; continue; }
echo "found $f"
donelogs/app.log has 2 lines
logs/db.log has 1 lines
no CSV files (the loop saw: logs/*.csv)
shopt -s nullglob is an alternative: it makes a non-matching glob expand to nothing.
while and until
while CONDITION repeats as long as the condition command succeeds; until repeats as long as it fails:
count=3
while (( count > 0 )); do
echo "countdown: $count"
(( count-- ))
done
attempt=1
until [ "$attempt" -gt 3 ]; do
echo "attempt $attempt"
attempt=$(( attempt + 1 ))
donecountdown: 3
countdown: 2
countdown: 1
attempt 1
attempt 2
attempt 3
A typical real-world until waits for something to become ready: until curl -sf http://localhost:8080/health; do sleep 1; done.
Reading a file line by line
while read is the right way to process lines, keeping spaces intact:
cat > inventory.csv <<'CSV'
keyboard,12,49.90
monitor,3,229.00
usb cable,40,4.50
CSV
while IFS=, read -r item qty price; do
printf '%-10s qty %3d value %7.2f\n' "$item" "$qty" "$(echo "$qty * $price" | bc)"
done < inventory.csvkeyboard qty 12 value 598.80
monitor qty 3 value 687.00
usb cable qty 40 value 180.00
IFS=,splits each line on commas (just for thereadcommand).-rkeeps backslashes literal: always use it.- The redirect
< filegoes afterdone.
Note:
cat file | while read ...also works, but the loop then runs in a subshell: variables changed inside are lost after the loop. Redirecting with< file(or< <(command)) avoids that.
printf '5\n10\n20\n' > amounts.txt
total=0
cat amounts.txt | while read -r n; do (( total += n )); done
echo "with a pipe: total=$total"
total=0
while read -r n; do (( total += n )); done < amounts.txt
echo "with a redirect: total=$total"with a pipe: total=0
with a redirect: total=35
break and continue
continue skips to the next iteration; break leaves the loop. Both accept a number for nested loops (break 2):
for n in 1 2 3 4 5 6 7 8 9; do
(( n % 2 == 0 )) && continue
(( n > 7 )) && break
printf '%s ' "$n"
done
echo
for row in 1 2 3; do
for col in 1 2 3; do
(( col > row )) && break
printf '%d' "$(( row * col ))"
printf ' '
done
echo
done1 3 5 7
1
2 4
3 6 9
Loops in one line
At the prompt, loops are often written on one line with ;:
for ext in jpg png gif; do touch "image.$ext"; done; ls image.*
i=0; while (( i < 3 )); do echo "line $i"; (( i++ )); doneimage.gif
image.jpg
image.png
line 0
line 1
line 2
Test yourself
Why doesn't for i in {1..$n} work?
- Brace expansion happens before variable expansion
- n must be quoted
- Ranges need seq
- It works fine
What is the correct way to read a file line by line?
- for line in $(cat file)
- while read -r line; do ...; done < file
- cat file | for line
- read file
Which loop runs while its condition FAILS?
- while
- for
- until
- select