Bird
Raised Fist0
Bash Scriptingscripting~15 mins

if-then-else in Bash Scripting - Deep Dive

Choose your learning style10 modes available
Overview - if-then-else
What is it?
The if-then-else statement in bash scripting lets the script make decisions. It checks if a condition is true or false. If true, it runs one set of commands; if false, it runs another set. This helps scripts behave differently based on different situations.
Why it matters
Without if-then-else, scripts would run the same way every time, no matter what. This would make automation rigid and unable to handle real-world changes or errors. If-then-else lets scripts adapt, making them smarter and more useful.
Where it fits
Before learning if-then-else, you should know basic bash commands and how to write simple scripts. After mastering if-then-else, you can learn loops and functions to build more complex scripts.
Mental Model
Core Idea
If-then-else lets a script choose between two paths based on a condition's truth.
Think of it like...
It's like deciding whether to take an umbrella before leaving the house: if it looks rainy, take it; else, leave it at home.
┌───────────────┐
│ Check condition│
└──────┬────────┘
       │True
       ▼
  ┌───────────┐
  │ Run 'then'│
  └────┬──────┘
       │
       ▼
     End
       ▲
       │False
  ┌────┴──────┐
  │ Run 'else'│
  └───────────┘
Build-Up - 7 Steps
1
FoundationBasic if statement syntax
🤔
Concept: Learn the simplest form of if statement to run commands when a condition is true.
In bash, an if statement starts with 'if', followed by a condition in square brackets, then 'then' and the commands to run if true. It ends with 'fi'. Example: if [ 5 -gt 3 ]; then echo "5 is greater than 3" fi
Result
5 is greater than 3
Understanding the basic syntax is key to writing any conditional logic in bash scripts.
2
FoundationTesting conditions with [ ]
🤔
Concept: Learn how to write conditions inside [ ] using comparison operators.
Conditions inside [ ] can compare numbers or strings. For numbers, use -eq (equal), -ne (not equal), -gt (greater than), -lt (less than), etc. For strings, use = or !=. Example: if [ "$name" = "Alice" ]; then echo "Hello Alice" fi
Result
If name is Alice, prints Hello Alice
Knowing how to write conditions lets you control when commands run.
3
IntermediateAdding else for alternate paths
🤔Before reading on: do you think else runs when the if condition is true or false? Commit to your answer.
Concept: Learn to add an else block to run commands when the condition is false.
The else block runs if the if condition is false. Syntax: if [ condition ]; then commands_if_true else commands_if_false fi Example: if [ $age -ge 18 ]; then echo "Adult" else echo "Minor" fi
Result
Prints Adult if age is 18 or more, else Minor
Adding else lets scripts handle both outcomes, making decisions complete.
4
IntermediateUsing elif for multiple conditions
🤔Before reading on: do you think elif can replace multiple nested if-else statements? Commit to your answer.
Concept: Learn to use elif to check several conditions in order.
Elif stands for 'else if' and lets you test more than two options. Syntax: if [ condition1 ]; then commands1 elif [ condition2 ]; then commands2 else commands_else fi Example: if [ $score -ge 90 ]; then echo "A" elif [ $score -ge 80 ]; then echo "B" else echo "C or below" fi
Result
Prints grade based on score ranges
Elif simplifies checking multiple conditions without deep nesting.
5
AdvancedCombining conditions with logical operators
🤔Before reading on: do you think && means 'or' or 'and' in bash conditions? Commit to your answer.
Concept: Learn to combine multiple conditions using AND (&&) and OR (||) inside if statements.
You can join conditions to check more complex logic: if [ $age -ge 18 ] && [ "$citizen" = "yes" ]; then echo "Eligible to vote" fi OR example: if [ "$color" = "red" ] || [ "$color" = "blue" ]; then echo "Color is red or blue" fi
Result
Runs commands only if combined conditions are true
Logical operators let you build precise decision rules in scripts.
6
AdvancedUsing command exit status in if
🤔Before reading on: do you think if can test the success of any command directly? Commit to your answer.
Concept: Learn that if can check if any command runs successfully by using its exit status.
In bash, commands return an exit status: 0 means success, non-zero means failure. If can test this directly: if grep -q "hello" file.txt; then echo "Found hello" else echo "Not found" fi
Result
Prints Found hello if grep finds the word, else Not found
Using command success in if lets scripts react to real command results, not just simple tests.
7
ExpertPitfalls with spaces and quoting in conditions
🤔Before reading on: do you think missing spaces inside [ ] causes errors or works fine? Commit to your answer.
Concept: Learn common syntax errors with spaces and quoting that cause if statements to fail unexpectedly.
In bash, spaces around [ and ] are mandatory. Also, variables should be quoted to avoid errors: Wrong: if [$var = value]; then echo "Yes" fi Right: if [ "$var" = "value" ]; then echo "Yes" fi Missing spaces or quotes can cause syntax errors or wrong results.
Result
Correct syntax runs as expected; wrong syntax causes errors or unexpected behavior
Knowing these syntax rules prevents frustrating bugs that waste time debugging.
Under the Hood
Bash if-then-else works by evaluating the condition command or test inside [ ]. This runs as a separate process that returns an exit status. If the status is zero (success), bash runs the 'then' block; if non-zero (failure), it runs the 'else' block if present. Logical operators && and || combine exit statuses to form complex conditions.
Why designed this way?
This design follows Unix philosophy where commands return exit codes to signal success or failure. Using exit status as condition lets bash scripts integrate any command's result into decision-making. It avoids complex parsing and keeps syntax simple and consistent.
┌───────────────┐
│ Evaluate test │
│ or command    │
└──────┬────────┘
       │ Exit status
       ▼
  ┌───────────┐
  │ 0 (true)  │─────► Run 'then' block
  └────┬──────┘
       │
       ▼
  ┌───────────┐
  │ Non-zero  │─────► Run 'else' block (if any)
  └───────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does if [ $var = value ] work without spaces inside the brackets? Commit yes or no.
Common Belief:You can write conditions without spaces inside the [ ] and it will work fine.
Tap to reveal reality
Reality:Bash requires spaces after [ and before ] for the condition to be parsed correctly. Missing spaces cause syntax errors.
Why it matters:Scripts fail to run or behave unpredictably, causing confusion and wasted debugging time.
Quick: Does if [ $var ] check if $var is empty or not? Commit yes or no.
Common Belief:Using if [ $var ] tests if the variable is empty or not.
Tap to reveal reality
Reality:If $var is empty, the condition becomes [ ], which is invalid syntax. You must quote variables: if [ "$var" ].
Why it matters:Unquoted variables can cause syntax errors or wrong condition evaluation, leading to bugs.
Quick: Does if command; then run the then block only if command outputs text? Commit yes or no.
Common Belief:The if statement checks if the command produces output to decide true or false.
Tap to reveal reality
Reality:If checks the command's exit status, not its output. A command can output nothing but still succeed (exit 0).
Why it matters:Misunderstanding this leads to wrong assumptions about script behavior and incorrect conditions.
Quick: Can you use && inside a single [ ] test to combine conditions? Commit yes or no.
Common Belief:You can write if [ condition1 && condition2 ] inside one pair of brackets.
Tap to reveal reality
Reality:Logical operators like && must be outside [ ] or use separate tests combined with &&. Inside [ ], && is not recognized.
Why it matters:Using && inside [ ] causes syntax errors or unexpected results.
Expert Zone
1
The exit status of a compound command like 'cmd1 && cmd2' affects if evaluation, allowing complex condition chaining.
2
Using [[ ]] instead of [ ] offers more powerful tests, like pattern matching and safer variable handling, but is bash-specific.
3
Short-circuit evaluation in if statements with && and || can optimize script performance by skipping unnecessary commands.
When NOT to use
If-then-else is not ideal for very complex decision trees; using case statements or functions can be clearer. For arithmetic-heavy conditions, let or (( )) syntax is better. Also, for portability to shells without [[ ]], avoid bash-specific features.
Production Patterns
In real scripts, if-then-else is used to check file existence, user input, command success, and environment variables. Scripts often combine if with functions and loops to build robust automation that handles errors gracefully.
Connections
Boolean Logic
If-then-else uses Boolean logic to decide which commands to run.
Understanding Boolean logic helps write correct conditions and combine them effectively.
Decision Trees (Computer Science)
If-then-else forms the basic building blocks of decision trees used in algorithms.
Recognizing if-then-else as a decision node helps understand how complex decisions are structured.
Everyday Choices
If-then-else mirrors how humans make choices based on conditions in daily life.
Seeing scripting decisions as everyday choices makes the concept intuitive and relatable.
Common Pitfalls
#1Missing spaces inside [ ] causing syntax errors.
Wrong approach:if [$var = value]; then echo "Yes" fi
Correct approach:if [ "$var" = "value" ]; then echo "Yes" fi
Root cause:Not knowing that bash requires spaces around [ and ] and quoting variables to parse conditions correctly.
#2Using unquoted variables leading to errors when variables are empty or contain spaces.
Wrong approach:if [ $name = "Alice" ]; then echo "Hi" fi
Correct approach:if [ "$name" = "Alice" ]; then echo "Hi" fi
Root cause:Not understanding that unquoted variables can break condition syntax or cause wrong comparisons.
#3Trying to use && inside a single [ ] test.
Wrong approach:if [ $age -ge 18 && $citizen = "yes" ]; then echo "Vote" fi
Correct approach:if [ $age -ge 18 ] && [ "$citizen" = "yes" ]; then echo "Vote" fi
Root cause:Confusing shell logical operators with test command syntax.
Key Takeaways
If-then-else lets bash scripts make decisions by running commands based on conditions.
Conditions inside [ ] must have spaces around brackets and variables should be quoted to avoid errors.
Else and elif blocks let scripts handle multiple outcomes cleanly without deep nesting.
If statements test command exit status, not output, enabling flexible checks of any command's success.
Understanding syntax and common pitfalls prevents bugs and makes scripts reliable and maintainable.

Practice

(1/5)
1. What does the if-then-else structure do in a bash script?
easy
A. It comments out lines in the script.
B. It repeats a set of commands multiple times.
C. It defines a function to reuse code.
D. It lets the script choose between two paths based on a condition.

Solution

  1. Step 1: Understand the purpose of if-then-else

    The if-then-else structure checks a condition and runs code based on whether the condition is true or false.
  2. Step 2: Compare with other options

    Repeating commands is done with loops, functions reuse code, and comments do not execute code.
  3. Final Answer:

    It lets the script choose between two paths based on a condition. -> Option D
  4. Quick Check:

    if-then-else = choose path [OK]
Hint: If you see a condition, it's likely if-then-else [OK]
Common Mistakes:
  • Confusing if-then-else with loops
  • Thinking if-then-else defines functions
  • Mixing comments with control flow
2. Which of the following is the correct syntax to start an if statement in bash?
easy
A. if [ condition ]; then
B. if { condition } then
C. if(condition) then
D. if condition then

Solution

  1. Step 1: Recall bash if syntax

    Bash requires spaces around brackets and a semicolon before then: if [ condition ]; then.
  2. Step 2: Check other options

    if(condition) then misses spaces and semicolon, B uses braces incorrectly, D misses brackets and semicolon.
  3. Final Answer:

    if [ condition ]; then -> Option A
  4. Quick Check:

    Spaces and semicolon needed [OK]
Hint: Remember spaces around [ ] and semicolon before then [OK]
Common Mistakes:
  • No spaces around brackets
  • Missing semicolon before then
  • Using parentheses or braces incorrectly
3. What will be the output of this script?
#!/bin/bash
x=5
if [ $x -gt 3 ]; then
  echo "Greater"
else
  echo "Smaller"
fi
medium
A. No output
B. Smaller
C. Greater
D. Syntax Error

Solution

  1. Step 1: Evaluate the condition

    The condition checks if x (5) is greater than 3, which is true.
  2. Step 2: Determine which branch runs

    Since condition is true, the script prints "Greater".
  3. Final Answer:

    Greater -> Option C
  4. Quick Check:

    5 > 3 = Greater [OK]
Hint: Check numeric comparison carefully [OK]
Common Mistakes:
  • Confusing -gt with -lt
  • Missing spaces causing syntax errors
  • Assuming else runs when condition is true
4. Find the error in this script:
#!/bin/bash
if [ $num -eq 10 ]
  echo "Ten"
else
  echo "Not Ten"
fi
medium
A. Missing then after condition
B. Wrong comparison operator
C. Missing fi at the end
D. No error

Solution

  1. Step 1: Check if statement syntax

    The if condition must be followed by then keyword to start the true block.
  2. Step 2: Identify missing part

    The script misses then after the condition line.
  3. Final Answer:

    Missing then after condition -> Option A
  4. Quick Check:

    if needs then [OK]
Hint: Always put then after condition in if [ ] [OK]
Common Mistakes:
  • Forgetting then keyword
  • Using wrong comparison operators
  • Missing fi to close if
5. You want a script that prints "Even" if a number is even, and "Odd" if it is odd. Which script correctly uses if-then-else to do this?
num=4
# Choose correct script
hard
A. if [ $num % 2 -eq 0 ]; then echo "Even" else echo "Odd" fi
B. if (( num % 2 == 0 )); then echo "Even" else echo "Odd" fi
C. if [ $num % 2 == 0 ]; then echo "Even" else echo "Odd" fi
D. if [ $num / 2 -eq 0 ]; then echo "Even" else echo "Odd" fi

Solution

  1. Step 1: Understand arithmetic evaluation in bash

    Using double parentheses (( )) allows arithmetic expressions and comparisons directly.
  2. Step 2: Check each option

    if [ $num % 2 -eq 0 ]; then echo "Even" else echo "Odd" fi uses % inside [ ] without arithmetic evaluation. if [ $num % 2 == 0 ]; then echo "Even" else echo "Odd" fi uses % inside [ ] without arithmetic evaluation. if [ $num / 2 -eq 0 ]; then echo "Even" else echo "Odd" fi uses / instead of % for modulus. if (( num % 2 == 0 )); then echo "Even" else echo "Odd" fi correctly uses (( )) with modulus and comparison.
  3. Final Answer:

    if (( num % 2 == 0 )); then echo "Even" else echo "Odd" fi -> Option B
  4. Quick Check:

    Use (( )) for arithmetic if [OK]
Hint: Use (( )) for math conditions in bash [OK]
Common Mistakes:
  • Using [ ] with arithmetic operators incorrectly
  • Confusing / with % for modulus
  • Missing then keyword
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard