if/elif/else
In this page:
Basic if/else
The if keyword runs the command that follows it and checks its exit status: 0 (success) takes the if branch, anything else falls through toward else. The block must be closed with fi.
Example: Basic if/else
#!/bin/bash
age=20
if [ "$age" -ge 18 ]; then
echo "Adult"
else
echo "Minor"
fi
Login to try C/C++/Java/PHP code in the editor
Adding elif Branches
elif (short for 'else if') lets you check additional conditions in sequence when the first if condition was false. Bash evaluates them top to bottom and executes only the first branch whose condition succeeds.
Example: Adding elif Branches
#!/bin/bash
score=75
if [ "$score" -ge 90 ]; then
echo "Grade: A"
elif [ "$score" -ge 75 ]; then
echo "Grade: B"
elif [ "$score" -ge 60 ]; then
echo "Grade: C"
else
echo "Grade: F"
fi
Login to try C/C++/Java/PHP code in the editor
if With Any Command, Not Just Tests
Because if just checks a command's exit status, you can put any command after it, not only [ ] or [[ ]] tests. This is commonly used to branch based on whether another program succeeded, like grep finding a match.
Example: if With Any Command, Not Just Tests
#!/bin/bash
if grep -q "root" /etc/passwd; then
echo "Found a line mentioning root"
else
echo "No match found"
fi
Login to try C/C++/Java/PHP code in the editor
Nested if for Multiple Checks
An if block can contain another complete if/fi block inside it, which is useful when a second condition only makes sense to check after the first one already passed. Keep nesting shallow for readability -- combining conditions with && is often clearer.
Example: Nested if for Multiple Checks
#!/bin/bash
logged_in=true
is_admin=false
if [ "$logged_in" = true ]; then
if [ "$is_admin" = true ]; then
echo "Welcome, admin"
else
echo "Welcome, user"
fi
fi
Login to try C/C++/Java/PHP code in the editor
- Forgetting the mandatory
; thenafter the condition (or puttingthenon the same line without a semicolon), which produces a syntax error. - Assuming
ifevaluates a boolean expression like in other languages; it actually runs a command and checks its exit status -- 0 means theifbranch is taken, anything else means it is not. - Leaving out
fito close theifblock, or misspelling it (it isifspelled backwards, notendif).
ifruns a command (often[ ]or[[ ]]) and takes the exit status to decide the branch, not a true/false value directly.- The block must end with
fi, and each condition line needs; thenorthenon its own line. elifchains additional conditions;elseprovides a fallback for when none matched.- Only the first matching branch (top to bottom) runs; later
elif/elseblocks are skipped once one matches.
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: