control-flow
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.
case WORD in PATTERN) ...;; PATTERN) ...;; *) ...;; esac Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| ;; | End the branch (no fall-through) — default |
| ;& | Fall through and execute the next branch's body |
| ;;& | Continue matching remaining patterns |
| *) | Default catch-all pattern |
Examples
case "$1" in start) do_start;; stop) do_stop;; *) echo usage;; esac Classic init-style command dispatcher.
case "$file" in *.jpg|*.png) echo image;; *.txt) echo text;; esac Multiple patterns per branch with |.
case "$var" in [0-9]*) echo starts_with_digit;; esac Glob character classes work in patterns.
shopt -s nocasematch; case "$x" in yes) echo ok;; esac Enable case-insensitive matching via nocasematch.
Gotcha
Patterns are shell globs, NOT regex — use [0-9] not \d, and * not .*. Always quote "$word" to avoid word splitting before matching.
Related
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.
[[ ]]
Bash-specific conditional expression with safer parsing, glob and regex matching, and short-circuit logical operators. No word splitting or filename expansion happens on the arguments, so quoting is far less error-prone than [ ] — but [[ ]] is not POSIX.
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.
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.