Conditional Statements in Bash: If-Else, Elif, and Flow Control
Conditional statements are the cornerstone of decision-making in shell scripting. They allow a script to evaluate specific conditions dynamically during execution and branch into different logical paths based on whether those conditions evaluate to true or false. This guide explores the syntax, structure, and practical implementation of if, else, and elif statements in Bash using real-world scripting examples.
1. Why Do We Need Conditional Statements?
In basic scripting, commands execute sequentially from top to bottom. However, real-world automation requires scripts to adapt to dynamic inputs, environmental changes, and system states.
Conditional statements allow your script to ask questions:
- Is a specific service running?
- Does a file exist on the system?
- Did the user provide valid input?
- Is a configuration value within an acceptable range?
Without conditional branching, a script cannot handle errors, validate inputs, or make intelligent decisions, rendering it fragile and static.
2. The Core Mental Model: The Loyalty Test Analogy
To understand how conditional logic branches, we can use a lighthearted real-world analogy based on characters from a popular TV show (Taarak Mehta Ka Ooltah Chashmah).
Real-Life Analogy: Jethalal's Loyalty Test
Imagine we want to write a script to check if the character Jethalal is loyal to his wife, Daya Bhabhi.
- The Primary Condition: We ask who Jethalal looked at (stored in the variable
bandi). If he looked at Daya Bhabhi, he is declared Loyal. - The Secondary Condition (The Second Chance): If he looked at someone else (e.g., Babita Ji), we don't immediately declare him disloyal. We check a second metric: his love percentage (
pyaar). If his love percentage is high enough (), he is still considered Loyal. - The Fallback (Else): If neither condition is met, he is declared Not Loyal.
Disclaimer (Infotainment Purpose): This example is designed purely for educational entertainment ("infotainment") to make abstract logical branching intuitive and memorable.
3. Syntax of Bash Conditional Statements
Bash has a distinct syntax for closing logical blocks. Unlike languages that use curly braces {} (like Java or C++) or indentation (like Python), Bash uses reversed keywords to close blocks.
The if-else Structure
if [ condition ]
then
# Code to execute if the condition is True
else
# Code to execute if the condition is False
fi
Key Syntax Rules:
- The
ifandfiKeywords: Anifstatement must always end withfi(ifspelled backward). This explicitly closes the conditional block. - The
thenKeyword: Everyifandelifstatement must be followed bythenon a new line (or on the same line separated by a semicolon;). - Spaces Inside Brackets: In Bash, the single bracket
[is actually an alias for thetestcommand. Therefore, you must leave a space after[and a space before]. Writing[$variable=="value"]will result in a syntax error.
4. Step-by-Step Evolution: The Basic If-Else Script
Let's write a script named check_if_jetha_loyal.sh that takes user input and performs a simple binary string comparison.
Step 1: Writing the Script
Create the file using a text editor like vim:
vim check_if_jetha_loyal.sh
Add the following code:
#!/bin/bash
# ==============================================================================
# DISCLAIMER: This script is for infotainment purposes only.
# ==============================================================================
# Prompt the user for input
read -p "Who did Jethalal look at? " bandi
# Perform string comparison
if [ "$bandi" == "Daya Bhabhi" ]
then
echo "Jethalal is loyal!"
else
echo "Jethalal is NOT loyal!"
fi
Step 2: Setting Permissions and Running the Script
Before executing the script, you must grant it execution permissions using chmod:
chmod 755 check_if_jetha_loyal.sh
Step 3: Execution and Output
If the user inputs "Daya Bhabhi":
./check_if_jetha_loyal.sh
Who did Jethalal look at? Daya Bhabhi
Jethalal is loyal!
If the user inputs "Babita Ji":
./check_if_jetha_loyal.sh
Who did Jethalal look at? Babita Ji
Jethalal is NOT loyal!
5. Step-by-Step Evolution: Adding Multi-Condition Logic with elif
In real-world scenarios, decisions are rarely binary. We often need to evaluate multiple alternative conditions using elif (else-if). Let's expand our script to evaluate both the person Jethalal looked at and his overall love percentage.
The Multi-Condition Script
#!/bin/bash
# ==============================================================================
# DISCLAIMER: This script is for infotainment purposes only.
# ==============================================================================
# Prompt the user for multiple inputs
read -p "Who did Jethalal look at? " bandi
read -p "Enter Jethalal's love percentage: " pyaar
# Multi-branch conditional logic
if [ "$bandi" == "Daya Bhabhi" ]
then
echo "Jethalal is loyal!"
elif [ "$pyaar" -ge 100 ]
then
echo "Jethalal is still loyal (Love percentage is $pyaar%)!"
else
echo "Jethalal is NOT loyal!"
fi
Note: In Bash, numeric comparisons use specific operators like
-ge(greater than or equal to) rather than standard mathematical symbols like>=when working inside single brackets[ ].
6. Real-World Debugging: The Missing then Pitfall
When writing conditional statements, syntax errors are common. A frequent mistake made by beginners (and experienced developers alike) is omitting the then keyword after an elif statement.
The Error Scenario
Consider this incorrect code block:
elif [ "$pyaar" -ge 100 ]
echo "Jethalal is still loyal!"
else
If you run this script, Bash will throw a syntax error:
./check_if_jetha_loyal.sh: line 15: syntax error near unexpected token `else'
./check_if_jetha_loyal.sh: line 15: `else'
Why Did This Fail?
Bash expects the keyword then immediately following any if or elif condition evaluation. Without then, Bash does not know where the condition evaluation ends and where the execution block begins. When it encounters else unexpectedly, the parser fails.
How to Fix It
Always ensure that every if and elif has a corresponding then:
elif [ "$pyaar" -ge 100 ]
then
echo "Jethalal is still loyal!"
7. Operators Reference Table
To build robust conditional statements, you must use the correct operators for string and numeric comparisons.
8. Complete Execution Flow Walkthrough
The following vertical flow diagram illustrates how Bash processes the multi-condition script step-by-step:
Summary and Key Takeaways
- Logical Branching: Conditional statements allow scripts to execute different blocks of code based on dynamic evaluations.
- The
fiTerminator: Everyifblock in Bash must be explicitly closed with thefikeyword. - The
thenRequirement: Everyifandelifstatement must be followed by a correspondingthenkeyword before writing the execution logic. - Spaces Matter: Always leave spaces inside the conditional brackets (e.g., [ "y" ]), as
[is a command that requires space-separated arguments. - String vs. Numeric Operators: Use
==and!=for comparing strings, and use flags like-eq,-ge, and-lefor comparing numbers inside single brackets. - Debugging Mindset: Syntax errors like
unexpected token elseare almost always caused by a missingthenkeyword or missing spaces inside the conditional brackets. Use these errors as clues to quickly locate and fix syntax issues.