Linuxlab

Loops in bash

Updated July 3, 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

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.

Used in

You need this in the lesson Bash: writing scripts.