control-flow
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.
if COMMAND; then ...; elif COMMAND; then ...; else ...; fi Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| then | Introduces the block run when the condition succeeds |
| elif | Chains an additional condition when the previous ones failed |
| else | Fallback block when no condition matched |
| fi | Closes the if construct (required) |
Examples
if [[ -f /etc/hosts ]]; then echo exists; fi Runs the then-branch when /etc/hosts is a regular file.
if grep -q root /etc/passwd; then echo found; else echo missing; fi Branches on grep's exit status; -q silences output.
if (( count > 10 )); then echo big; elif (( count > 0 )); then echo small; else echo empty; fi Arithmetic conditions using (( )) with chained elif.
if cmd1 && cmd2; then echo both_ok; fi Compound condition; then-branch runs only if both commands succeed.
Gotcha
The condition is a COMMAND, not an expression — 'if $var' runs $var as a command. Use [[ ]] or (( )) to test values, and always quote variables inside [ ].
Related
[[ ]]
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.
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.
(( )) 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.
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.