shBash
BeginnerLesson 5 of 15

Loops: for, while, until – Bash

Work through lists, number ranges, files and lines.

for runs over a list of words. With brace expansion {1..5} and seq you generate numbers, with globs like *.txt all matching files (the shell replaces the pattern before execution).

for farbe in red green blue; do
  echo "Color: $farbe"
done

for i in {1..3}; do echo "Round $i"; done      # 1 2 3
for ((i = 0; i < 3; i++)); do echo "Index $i"; done   # C style (Bash only)

for datei in *.txt; do
  echo "Processing $datei"
done

while runs as long as the command succeeds; until runs until it succeeds. break ends the loop, continue jumps to the next round. To read a file line by line, use while read:

n=0
while (( n < 5 )); do
  n=$((n + 1))
  (( n % 2 == 0 )) && continue
  echo "odd: $n"          # 1 3 5
done

# read a file line by line
while IFS= read -r zeile; do
  echo "Line: $zeile"
done < server.log

# wait for something
until [[ -f fertig.txt ]]; do sleep 1; done
WarningDo not write for f in $(ls): file names with spaces fall apart into several words. Use globs (for f in *) or find ... -print0. If a glob matches nothing, the pattern stays literal (*.txt) – check with [[ -e "$f" ]] || continue or shopt -s nullglob.
TipIFS= and read -r prevent leading whitespace from being trimmed and backslashes from being interpreted – this is the standard form for reading line by line.