TExcelTAD
Home › Linux & Bash › Bash Loops

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

bash · try it yourself
for fruit in apple banana cherry; do
  echo "I like $fruit"
done
for file in report.txt "my notes.txt"; do
  echo "processing: $file"
done
I 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

bash · try it yourself
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; echo
1 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:

bash · try it yourself
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"
done
logs/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:

bash · try it yourself
count=3
while (( count > 0 )); do
  echo "countdown: $count"
  (( count-- ))
done
attempt=1
until [ "$attempt" -gt 3 ]; do
  echo "attempt $attempt"
  attempt=$(( attempt + 1 ))
done
countdown: 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:

bash · try it yourself
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.csv
keyboard   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 the read command).
  • -r keeps backslashes literal: always use it.
  • The redirect < file goes after done.

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.

bash · try it yourself
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):

bash · try it yourself
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
done
1 3 5 7
1
2 4
3 6 9

Loops in one line

At the prompt, loops are often written on one line with ;:

bash · try it yourself
for ext in jpg png gif; do touch "image.$ext"; done; ls image.*
i=0; while (( i < 3 )); do echo "line $i"; (( i++ )); done
image.gif
image.jpg
image.png
line 0
line 1
line 2

Test yourself

Why doesn't for i in {1..$n} work?

  1. Brace expansion happens before variable expansion
  2. n must be quoted
  3. Ranges need seq
  4. It works fine

What is the correct way to read a file line by line?

  1. for line in $(cat file)
  2. while read -r line; do ...; done < file
  3. cat file | for line
  4. read file

Which loop runs while its condition FAILS?

  1. while
  2. for
  3. until
  4. select