control-flow
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.
break [N] | continue [N] Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| break | Exit the current loop entirely |
| continue | Skip rest of body and start next iteration |
| N | Apply to the Nth enclosing loop (default 1) |
| exit status | Both always return 0 |
Examples
for i in 1 2 3; do (( i == 2 )) && break; echo "$i"; done Prints only 1 — loop exits when i reaches 2.
for f in *; do [[ -d $f ]] && continue; process "$f"; done Skip directories, process only files.
for a in x y; do for b in 1 2; do break 2; done; done break 2 exits both nested loops at once.
for i in {1..5}; do (( i % 2 )) && continue; echo "$i"; done Prints only even numbers 2 and 4.
Gotcha
'break' inside a function does NOT return from the function — it only breaks the loop. In an until loop, continue re-tests the condition — make sure loop state advances or you'll spin forever.
Related
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.
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.
return
Exits a shell function or sourced script and returns exit status N (0-255). Without N, returns the exit status of the last command executed in the function.
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.