control-flow
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.
while COMMAND; do ...; done | until COMMAND; do ...; done Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| do / done | Delimits the loop body |
| while read | Idiomatic line-by-line input consumption |
| while :; | Infinite loop (: is the true builtin) |
| until | Same shape as while but inverts the condition |
| break / continue | Exit or skip to the next iteration |
Examples
while read -r line; do echo "$line"; done < file.txt Reads file.txt line by line; -r prevents backslash mangling.
while (( i < 10 )); do echo "$i"; ((i++)); done Arithmetic-tested loop with in-place increment.
until curl -sf http://localhost:8080/health; do sleep 2; done Poll a health endpoint every 2s until it returns 2xx.
while IFS=, read -r a b c; do echo "$a $b"; done < data.csv CSV parsing: IFS=, splits on commas per iteration.
Gotcha
Piping into 'while' (cmd | while read ...) runs the loop in a subshell — variable changes inside are lost. Use process substitution 'while ... done < <(cmd)' to preserve them.
Related
read
Reads a single line from stdin (or a file descriptor) and splits it into the given variables using IFS. The workhorse for line-by-line input processing and interactive prompts.
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.
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.