control-flow
for ... in / for ((;;))
Iterates a variable over a word list, glob, or command substitution; the C-style form iterates using arithmetic. Executes the body once per iteration and exits with the status of the last command run.
for VAR in LIST; do ...; done | for ((i=0; i<N; i++)); do ...; done Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| in LIST | Word list to iterate (globs, brace expansion, $(...) all valid) |
| do / done | Delimits the loop body |
| for ((;;)) | C-style arithmetic loop with init/condition/update |
| "$@" | Iterate positional parameters safely with quoting |
Examples
for f in *.log; do gzip "$f"; done Iterates every .log file; quote $f to survive spaces.
for i in {1..5}; do echo "$i"; done Brace expansion produces 1 2 3 4 5 as separate words.
for ((i=0; i<10; i++)); do echo "$i"; done C-style loop — pure arithmetic, no word splitting.
for arg in "$@"; do process "$arg"; done Iterates positional parameters; quotes prevent word splitting.
Gotcha
'for f in $(ls)' breaks on filenames with spaces — use globs like 'for f in *' instead. If the glob matches nothing you get the literal pattern; enable 'shopt -s nullglob' for an empty list.
Related
while / until / do / done
Repeats the body while (or until) the condition command exits 0. 'while' loops while the condition succeeds; 'until' is the inverse and is idiomatic for polling until a service becomes ready.
(( )) arithmetic
Bash arithmetic evaluation — treats operands as integers and supports C-style operators (+, -, *, /, %, **, <<, >>, &, |, ^, &&, ||, !, ==, !=, <, >, ternary). (( )) returns exit status 0 if EXPR is non-zero, 1 if zero; $(( )) substitutes the result as a string.
break / continue
Loop-control builtins for for/while/until/select loops. 'break' exits the enclosing loop; 'continue' skips to the next iteration; both accept an integer N to affect N nested loops at once.
if / then / elif / else / fi
Conditional branching based on the exit status of a command (0 = true, non-zero = false). Runs the then-branch when the tested command succeeds; supports optional elif and else clauses and must be terminated with fi.
case ... esac
Pattern-matches a word against glob-style patterns (not regex) and runs the first matching branch. Terminators control fall-through: ;; ends, ;& falls through, ;;& tries next pattern.