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

← All Bash builtins · Linux commands