Python Conditional Branching: if, elif, else & case Statements
Decision making in Bash is performed via `if-elif-else-fi` blocks and `case-esac` pattern matching. The `case` statement is especially clean for parsing CLI arguments, flags, and menu choices without messy nested if statements.
"`if-else` is like a fork in the road with 2 directions; `case` is a multi-track train switchyard routing trains to 10 different platforms based on their destination sign."
Deep Dive: How It Works
if Syntax: `if [[ condition ]]; then ... elif [[ condition2 ]]; then ... else ... fi`. Note the semicolons or newlines before `then`.
case Syntax: `case "$var" in pattern1) cmd ;; pattern2|pattern3) cmd ;; *) default_cmd ;; esac`. Double semicolons `;;` terminate each branch.
Exit Status Evaluation: `if grep -q "text" file; then` tests the actual command exit code directly without needing `[[ ]]`.
Syntax Blueprint
if [[ "$ENV" == "production" ]]; then echo "Prod mode" elif [[ "$ENV" == "staging" ]]; then echo "Staging mode" else echo "Dev mode" fi case "$ACTION" in start) start_server ;; stop) stop_server ;; restart) stop_server; start_server ;; *) echo "Unknown action" ;; esac
Use if/elif for boolean logic and case/esac for multi-branch option parsing.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Forgetting `fi` to close an `if` block or `esac` to close a `case` block.Why it happens: Bash uses reversed keywords (`if` -> `fi`, `case` -> `esac`) to close blocks.
How to fix: Ensure every `if` pairs with `fi` and `case` pairs with `esac`.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Branch with a case Statement
Set `MODE="test"`.
Create a case statement that matches `"test"` and echoes "Running in test mode".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.