← Back to Bash Course | Chapter 3: Control Flow | Lesson 2 of 14

if/elif/else

if/elif/else lets your script choose which block of commands to run based on whether a condition is true or false.

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

bash
#!/bin/bash
age=20
if [ "$age" -ge 18 ]; then
    echo "Adult"
else
    echo "Minor"
fi

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

bash
#!/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

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

bash
#!/bin/bash
if grep -q "root" /etc/passwd; then
    echo "Found a line mentioning root"
else
    echo "No match found"
fi

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

bash
#!/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
Common Mistakes
  1. Forgetting the mandatory ; then after the condition (or putting then on the same line without a semicolon), which produces a syntax error.
  2. Assuming if evaluates a boolean expression like in other languages; it actually runs a command and checks its exit status -- 0 means the if branch is taken, anything else means it is not.
  3. Leaving out fi to close the if block, or misspelling it (it is if spelled backwards, not endif).
Chapter Summary
  • if runs 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 ; then or then on its own line.
  • elif chains additional conditions; else provides a fallback for when none matched.
  • Only the first matching branch (top to bottom) runs; later elif/else blocks are skipped once one matches.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.