0
0
Bash Scriptingscripting~15 mins

if-then-else in Bash Scripting - Deep Dive

Choose your learning style9 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.