if, elif and else
An if statement chooses which commands to run by checking the exit status of a command or command list. Status 0 means success (true for the condition); nonzero means false. Write if command; then commands; fi. An optional elif checks another condition only if earlier ones failed; else handles the remaining cases. Conditions may print output, but it is the status, not the printed text, that decides the branch. A newline can replace the semicolon before then. The status of the whole if is the status of the last command executed in a selected branch, or zero if no condition succeeds and no branch runs.
Practical examples
Run each example separately in Bash 5.2 in a fresh empty practice directory. Tests use default shell options and C locale. Output is shown separately; do not enter it as code.
Choose a branch
Expected stdout:
readyOnly the successful branch runs.
Try the next condition
if false; then printf '%s\n' firstelif true; then printf '%s\n' secondelse printf '%s\n' fallbackfiExpected stdout:
secondThe first failure leads to the elif.
Output is not truth
Expected stdout:
falsesuccessprintf prints the word false but succeeds.
Common mistakes
if false does not mean a syntax error. It simply skips the then branch. Do not compare $? after intervening commands; put the command itself in the condition.
Practice
Use false, then true in an elif, then an else. Print three different labels and predict which one appears.
Next: String comparisons with test and brackets