Loops and Iteration

Loops and Iteration in Bash: --- A drinks factory runs a rotary filling carousel. Empty bottles arrive on a conveyor, and the carousel is a slowly turning…


The Analogy: The Bottling Line's Filling Carousel

A drinks factory runs a rotary filling carousel. Empty bottles arrive on a conveyor, and the carousel is a slowly turning wheel with a fixed number of filling heads around its rim. As the wheel turns, each head meets a bottle, opens its valve for a measured dose, closes, and moves on. The carousel does not decide how many bottles exist; it simply keeps turning, and every bottle that arrives at a head gets the same sequence of actions applied to it. This is a for loop: a known collection of items -- the bottles queued for this batch -- and one body of work performed once per item.

Next to the carousel is a different machine: a holding tank that must be pumped down before cleaning. An operator opens the drain and watches a sight glass. The pump runs while the level is above the low mark, and stops the moment the level drops below it. Nobody counted the litres in advance; the machine repeats an action and re-checks a condition each time around. This is a while loop -- keep going as long as a test succeeds -- and its mirror image, the until loop, which keeps going until a test starts to succeed, like waiting until a pressure gauge finally reaches its set point.

A third pattern runs at the goods-out desk, where a clerk works down a delivery manifest one line at a time. The clerk does not load the whole sheet into their head; they read the next line, act on it, then read the line after, until the sheet runs out. Each line has fields -- product code, quantity, destination -- that the clerk separates as they read. This is the while read loop over a stream, the workhorse for processing files and command output line by line, splitting each line into fields as it arrives.

The failure mode on every one of these machines is the same in spirit: the loop that keeps running when it should have stopped, or stops when it should have kept running. A carousel head whose valve sticks open floods the line. A drain pump whose sight glass is misread runs dry and burns out. A clerk who miscounts the manifest either skips the last delivery or invents one that is not there. In the shell these become the infinite while whose condition never flips, the for that word-splits one filename with a space into two bogus items, and the while read that silently drops the final line when the file has no trailing newline. Each is a small logic slip with an outsized, quiet cost, and each has a specific idiom that prevents it.


Syntax or Core Structure

Bash has three loop keywords. for walks a list of words that is known before the loop starts. while and until repeat as long as (or until) a command succeeds, re-testing each pass. All three use do and done to bracket the body.

#!/usr/bin/env bash
# for over an explicit word list
for station in fill cap label inspect; do
  printf 'station: %s\n' "$station"
done

# for over a brace-expanded range
for n in {1..4}; do
  printf 'bottle %d\n' "$n"
done

# C-style for, when you want a counter
for (( i = 0; i < 3; i++ )); do
  printf 'index %d\n' "$i"
done

The first form is the one to reach for. The word list after in is built by the shell's normal expansions -- brace, glob, variable -- before the loop runs even once, so for n in {1..4} is identical to having typed for n in 1 2 3 4. The C-style for (( )) is a separate construct that lives in arithmetic, useful when you genuinely need an index rather than a list of values.

Output:

station: fill
station: cap
station: label
station: inspect
bottle 1
bottle 2
bottle 3
bottle 4
index 0
index 1
index 2

Technical Depth: When the List is Built, and Where the Body Runs

Before the details, a map of which loop fits which shape of problem. The distinction that matters is whether the number of iterations is known before the loop starts or only discovered as it runs.

LoopIterates overCount known whenTypical use
for x in lista fixed word listbefore the first passfiles from a glob, array elements, a range
for (( i=0; ... ))an arithmetic counterbefore the first passwhen the index itself is needed
while cmdrepeats while a test succeedsonly as it runsdraining a queue, polling, reading a stream
until cmdrepeats until a test succeedsonly as it runswaiting for a condition to become true

while and until re-check every pass

A for loop fixes its list once. A while loop asks its question again on every iteration, which is what makes it right for conditions that change as the loop runs. until is the same machine with the test inverted: it loops while the command fails and stops when it first succeeds.

#!/usr/bin/env bash
level=5
while (( level > 0 )); do
  printf 'level %d\n' "$level"
  level=$(( level - 1 ))
done
printf 'stopped at %d\n' "$level"

count=0
until (( count >= 3 )); do
  printf 'count %d\n' "$count"
  count=$(( count + 1 ))
done

Output:

level 5
level 4
level 3
level 2
level 1
stopped at 0
count 0
count 1
count 2

The while prints five lines and stops when level reaches 0, because the test is checked before each pass and 0 > 0 is false. The until prints three lines and stops when count reaches 3. The body must move the loop toward its exit condition; forget the level=$(( level - 1 )) line and the carousel never stops turning.

The line-reading idiom, and why each piece is there

Reading a file line by line is the most common loop in shell scripting, and the correct incantation has three deliberate parts that each defend against a specific mangling.

#!/usr/bin/env bash
printf 'alpha 10\nbeta 20\ngamma 30\n' > data.txt

while IFS= read -r line; do
  printf 'got: [%s]\n' "$line"
done < data.txt

# splitting each line into named fields
while read -r name value; do
  printf '%s -> %d\n' "$name" "$value"
done < data.txt

Output:

got: [alpha 10]
got: [beta 20]
got: [gamma 30]
alpha -> 10
beta -> 20
gamma -> 30

The three parts of while IFS= read -r line each matter. Setting IFS= for the duration of the read stops leading and trailing whitespace from being stripped, so the line arrives exactly as stored. The -r flag stops backslashes from being interpreted as escapes, so a Windows path or a regex in the data survives intact. And redirecting with < data.txt rather than cat data.txt | keeps the loop in the current shell, which the next subsection shows is not optional. When you name more than one variable, read splits on IFS and the last variable soaks up everything left over.

The pipe-into-while trap: a subshell eats your variables

This is the single most surprising loop bug in bash. Each stage of a pipeline runs in its own subshell, so a while on the right of a | cannot change variables in the parent.

#!/usr/bin/env bash
printf 'x\ny\nz\n' > items.txt

seen=0
cat items.txt | while read -r _; do
  seen=$(( seen + 1 ))
done
printf 'after pipe, seen=%d\n' "$seen"

seen=0
while read -r _; do
  seen=$(( seen + 1 ))
done < items.txt
printf 'after redirect, seen=%d\n' "$seen"

Output:

after pipe, seen=0
after redirect, seen=3

Both loops run their body three times. The piped version increments a seen that lives in the subshell created for the right side of the pipe, and that subshell evaporates when the pipeline ends, taking the count with it -- so the parent still reads 0. The redirected version runs the loop in the current shell, so the count survives. Redirect from a file, or use process substitution, whenever the loop needs to leave a mark on the surrounding script.

Looping over a glob, and the empty-match question

A for over a glob pattern is the natural way to process files, but you must decide what should happen when nothing matches. By default bash leaves an unmatched pattern as a literal string, so the loop runs once with the pattern itself as the value -- rarely what you want.

#!/usr/bin/env bash
mkdir -p logs; : > logs/a.log; : > logs/b.log

for f in logs/*.log; do
  printf 'found: %s\n' "$f"
done

shopt -u nullglob
for f in logs/*.nomatch; do
  printf 'default leaves the pattern literal: [%s]\n' "$f"
done

shopt -s nullglob
ran=0
for f in logs/*.nomatch; do ran=1; done
printf 'with nullglob, body ran %d times\n' "$ran"

Output:

found: logs/a.log
found: logs/b.log
default leaves the pattern literal: [logs/*.nomatch]
with nullglob, body ran 0 times

The first loop finds the two real files. The second, with the default behaviour, runs once with the literal unmatched pattern, so a naive rm "$f" there would fail on a file that does not exist. Setting shopt -s nullglob makes an unmatched pattern expand to nothing, so the loop body is skipped entirely -- almost always the safer choice when iterating files.

Iterating an array by value and by index

Arrays need the quoted [@] expansion to keep elements with spaces intact, and ${!array[@]} to walk the indices.

#!/usr/bin/env bash
tasks=("clean tank" "fill bottles" "apply labels")

for t in "${tasks[@]}"; do
  printf 'task: [%s]\n' "$t"
done
printf 'count: %d\n' "${#tasks[@]}"

for i in "${!tasks[@]}"; do
  printf '  %d: %s\n' "$i" "${tasks[i]}"
done

Output:

task: [clean tank]
task: [fill bottles]
task: [apply labels]
count: 3
  0: clean tank
  1: fill bottles
  2: apply labels

The quotes around "${tasks[@]}" are load-bearing: without them, clean tank would split into two loop items. This is the same word-splitting hazard that makes for f in $(ls) a well-known bug -- a filename with a space becomes two bogus iterations. Iterate arrays with [@] and globs directly, never by parsing the output of ls.


Real World Example: A Batch Report Over a Set of Log Files

This program combines the two loops you will reach for most often: an outer for walking a set of files, and an inner while read splitting each file into fields. It tallies sensor readings across several logs, counting how many of each metric appeared, their running total, and how many crossed a threshold, then prints a report with a stable row order.

#!/usr/bin/env bash
# batch-report.sh -- tally sensor readings across a set of log files
set -u
work=$(mktemp -d); trap 'rm -rf "$work"' EXIT

printf 'temp 71\ntemp 74\ntemp 92\n'     > "$work/line-1.log"
printf 'temp 68\npressure 30\ntemp 88\n' > "$work/line-2.log"
printf 'pressure 45\npressure 51\n'       > "$work/line-3.log"

threshold=85
declare -A count sum over

files=0
for f in "$work"/*.log; do
  files=$(( files + 1 ))
  while read -r metric value; do
    count[$metric]=$(( ${count[$metric]:-0} + 1 ))
    sum[$metric]=$(( ${sum[$metric]:-0} + value ))
    if (( value > threshold )); then
      over[$metric]=$(( ${over[$metric]:-0} + 1 ))
    fi
  done < "$f"
done

printf 'scanned %d files\n' "$files"
printf '%-10s %6s %8s %6s\n' metric count average over
for metric in $(printf '%s\n' "${!count[@]}" | sort); do
  c=${count[$metric]}; s=${sum[$metric]}
  printf '%-10s %6d %8d %6d\n' \
    "$metric" "$c" "$(( s / c ))" "${over[$metric]:-0}"
done

total=0
for metric in "${!count[@]}"; do
  total=$(( total + count[$metric] ))
done
printf 'total readings: %d\n' "$total"

Output:

scanned 3 files
metric      count  average   over
pressure        3       42      0
temp            5       78      2
total readings: 8

Trace the outer loop first. It walks three files, incrementing files each pass, and the inner while read -r metric value splits every line into a name and a number. The associative arrays accumulate per metric: temp appears five times across the three files and pressure three times, which is why the total is eight. The ${count[$metric]:-0} default lets the first sighting of a metric start from zero instead of erroring on an unset key.

The report loop is where the stable order comes from. Iterating "${!count[@]}" directly would visit the keys in an unspecified hash order that can differ between runs, so the metric names are piped through sort first, giving pressure before temp every time. The averages are integer divisions: temp sums to 393 over 5 readings, and 393 / 5 truncates to 78, not 78.6. Two temp readings, 92 and 88, exceed the threshold of 85, so the over-count is 2.

The script is honest about its limits, and two of them are real defects rather than rough edges. First, the average is computed with integer division, so it silently drops the fractional part -- a run of readings averaging 78.9 reports 78, and nothing warns you the number was rounded down. For a report that drives decisions, that truncation is a genuine accuracy bug, not a display nicety. Second, the arithmetic accepts whatever sits in the value field: a malformed line such as temp xy makes $(( sum + value )) treat xy as 0, so a corrupt reading vanishes into the tally with no error and no flag, quietly biasing every average that includes it. A production version would validate each value against a numeric pattern before adding it, and would carry a scaled integer or shell out to a fixed-point tool for the averages.


Common Mistakes

  1. Piping into a while loop and expecting variables to persist. The right side of a pipe runs in a subshell, so counters and flags set inside cat file | while read ... are lost when the pipeline ends. Redirect with done < file or use process substitution so the loop runs in the current shell.
  1. Writing for f in $(ls) to iterate files. Command substitution word-splits on whitespace, so a filename with a space becomes two iterations, and a glob character in a name gets expanded again. Loop over the glob directly with for f in *.log, which handles spaces and special characters correctly.
  1. Forgetting -r on read. Without -r, read treats backslashes as escape characters, so a path like a Windows share or any data containing a backslash is silently corrupted. Use read -r unless you have a specific reason to want escape processing.
  1. Dropping the last line of a file with no trailing newline. A plain while read -r line exits when read hits end-of-file, and if the final line lacks a newline it is read into the variable but the loop still exits without processing it. Guard with while read -r line || [ -n "$line" ] when the input may be newline-terminated or not.
  1. Building an infinite loop by forgetting to advance the state. A while (( n > 0 )) whose body never decrements n runs forever. Every while and until body must contain something that moves the condition toward its exit, and it is worth reading the body once to confirm that it does.
  1. Not quoting "${array[@]}" when iterating. Unquoted, the expansion word-splits every element, so "clean tank" becomes two loop passes. Always quote the [@] expansion, and use "${!array[@]}" when you need the indices rather than the values.
  1. Assuming an unmatched glob disappears. By default an unmatched pattern like *.log is left literal, so the loop runs once with the pattern text itself. Set shopt -s nullglob when an empty match should skip the loop body, or check [ -e "$f" ] inside it.
  1. Modifying IFS globally instead of per-command. Writing IFS=, on its own line changes splitting for the rest of the script and surprises later code. Scope it to the one command with IFS=, read -r ..., which restores the old value automatically once read returns.
  1. Using a C-style for (( )) when a list would be clearer. Counting indices to then index into an array reintroduces off-by-one errors that for item in "${array[@]}" avoids entirely. Reserve the arithmetic for for when you truly need the number, not the element.

Best Practices

  • Prefer for item in "${list[@]}" over index arithmetic. Iterating values directly sidesteps off-by-one mistakes and reads as the intent. Drop to a C-style counter only when the index itself is the thing you need.
  • Always read with while IFS= read -r line. The IFS= preserves surrounding whitespace, the -r preserves backslashes, and the combination is the only form that returns a line byte-for-byte as stored. Make it your reflex spelling.
  • Feed loops with redirection or process substitution, not a pipe. When the loop must update variables that outlive it, run it in the current shell with done < file or done < <(command) rather than command | while.
  • Set nullglob when looping over files that might not exist. It turns an empty match into zero iterations instead of one bogus pass on the literal pattern, which is almost always what file-processing loops want.
  • Guard the trailing-newline case for real-world input. Data that arrives from other systems may lack a final newline; the || [ -n "$line" ] guard on the while read makes the loop robust to both forms without extra bookkeeping.
  • Keep report output in a deterministic order. Associative-array keys iterate in an unspecified order, so pipe them through sort before printing. Reproducible output is what makes a report diffable and a test assertable.
  • Move the exit condition forward visibly. Put the increment or decrement that advances a while loop where a reader can see it near the top or bottom of the body, so the reason the loop terminates is obvious at a glance.
  • Validate fields before doing arithmetic on them. A value read from a file is text; check it against a numeric pattern before feeding it to (( )), because bash treats an unparseable value as 0 and will fold silent corruption into your totals.

Practice Exercises

  1. The two-loop word counter. Write a script that loops over every .txt file in a directory with a for glob, and for each file uses a while IFS= read -r line loop to count its lines and total words. Print one row per file and a grand total at the end, and set nullglob so a directory with no text files prints a clean zero.
  1. Prove the subshell trap. Write a script that counts the lines of a file two ways: once with cat file | while read and once with while read; done < file, printing the counter after each. Confirm the piped version reports zero, then add a one-line comment explaining which shell each loop body ran in.
  1. A retry-until-ready loop. Simulate waiting for a resource by writing a script that creates a marker file only on its third check. Use an until [ -e marker ] loop with a counter, print each attempt, and stop once the marker appears -- then explain in a comment how you would add a maximum-attempts guard so the loop cannot run forever.
  1. Stable frequency table. Given a file of one word per line, write a script that uses a while read loop to fill an associative array of counts, then prints the words and counts in sorted order. Extend it to also print the single most frequent word, and note in a comment why iterating the array without sorting would make the output differ between runs.