Loops in bash

Updated November 1, 2026

A loop repeats commands. for walks a list of words, while read walks the lines of a stream.

for x in alpha beta; do echo "$x"; done

while read -r line; do
  echo "line: $line"
done < ~/data/words.txt

Sample output

$ cat data/words.txt
alpha beta
gamma
$ for x in $(cat data/words.txt); do echo "[$x]"; done
[alpha]
[beta]
[gamma]
$ while read -r line; do echo "[$line]"; done < data/words.txt
[alpha beta]
[gamma]

How it works: why not for x in $(cat file)

Writing for x in $(cat file) reads the whole file, then bash splits it on spaces and expands patterns. A line with a space falls apart, and a * turns into a list of files. while read -r line reads exactly one line at a time and expands nothing - that is the right way to walk lines.

Common mistakes

cat file | while read ... loses everything the loop counted. The right side of a pipeline runs in its own subshell, so n=0; cat data/words.txt | while read -r l; do n=$((n+1)); done; echo "n=$n" prints n=0. The same loop with a redirect, done < data/words.txt, prints n=2. Feed the file in with <, not with cat |.

The last line disappears when the file has no final newline. For a file built with printf "one\ntwo", the loop while read -r l runs once and prints only [one]: on the tail without \n the read command returned failure, so the body never ran. The guard while read -r l || [ -n "$l" ] saves it.

for f in *.txt in a directory with no matches runs once with $f set to the literal string *.txt. The loop prints [*.txt] and the command inside it fails: ls: cannot access '*.txt': No such file or directory, exit code 2. Either start the body with [ -e "$f" ] || continue, or turn on shopt -s nullglob so the loop runs zero times.

Used in

You need this in the lesson Bash: writing scripts.