Conditionals are the backbone of any robust programming language. They allow you to control program flow by performing different actions based on certain conditions being met.
In Bash scripting, if, elif (else if), and else statements provide the functionality for conditionals. But mastering them is key to writing effective Bash scripts.
This comprehensive guide will take you through everything you need to know to leverage if, elif, and else like a pro!
We‘ll start by understanding the basics, then build up to more advanced usages and best practices when working with conditional logic in Bash.
So let‘s get started!
If Statement Basics
The if statement is used to check if a test condition evaluates to true and execute a block of code if the result is true.
Here is the basic syntax:
if [[ condition ]]; then
# Code to execute if condition is true
fi
Let‘s break this down:
if: Starts the if statement block[[ condition ]]: This is the test condition to check. It can be any valid Bash conditional expression. More on this soon.then: Execute the following code block if the test condition is truefi: Closes the if statement block
The code between then and fi is the body of the if statement. This code will run if the condition test returns true.
Common Condition Tests
The test condition inside [[ ]] supports many comparison operators and can evaluate both numeric and string expressions.
Here are some common condition tests:
1. String equality
string1 = "foo"
string2 = "bar"
if [[ $string1 == "$string2" ]]; then
echo "Strings are equal"
fi
The == operator checks for string equality.
2. Numeric comparisons
num=10
if [[ $num -gt 5 ]]; then
echo "$num is greater than 5"
fi
Use -eq, -ne, -lt, -le, -gt, -ge for numeric comparisons like equal, not equal, less than etc.
3. File checks
if [[ -f "file.txt" ]]; then
echo "File exists"
fi
-f, -d, -r, -w, -x check if a file/directory exists, is readable/writable/executable.
4. Compound conditions
# User is bob AND uid is 1000
if [[ $USER == "bob" && $UID -eq 1000 ]]; then
echo "You are bob"
fi
# User is bob OR admin
if [[ $USER == "bob" || $USER == "admin" ]]; then
echo "You are bob or admin"
fi
Use && for AND, || for OR logical conditions.
The [[ ]] syntax offers a lot of flexibility in the conditions you can test! Now let‘s look at some complete examples.
If Statement Examples
- Basic string check
read -p "Enter name: " name
if [[ $name == "John" ]]; then
echo "Welcome John!"
fi
- Numeric check with elif
read -p "Enter age: " age
if [[ $age -lt 18 ]]; then
echo "Minor"
elif [[ $age -ge 18 && $age -le 30 ]]; then
echo "Youth"
elif [[ $age -gt 30 && $age -le 60 ]]; then
echo "Middle aged"
else
echo "Senior citizen"
fi
- Reading a file
file="test.txt"
if [[ -f "$file" ]]; then
echo "$file found!"
cat "$file"
else
echo "$file not found!"
fi
- User input validation
read -p "Enter y/n: " ans
if [[ $ans == "y" || $ans == "Y" ]]; then
echo "You entered yes"
elif [[ $ans == "n" || $ans == "N" ]]; then
echo "You entered no"
else
echo "Invalid input"
fi
These examples give you a sense of all the things you can do with if statements in your Bash scripts.
Elif Statement
The elif statement, short for "else if", allows you to check for multiple conditions and execute different code blocks based on which condition evaluates to true.
The basic syntax is:
if [[ condition1 ]]; then
# Code1
elif [[ condition2 ]]; then
# Code2
elif [[ condition3 ]]; then
# Code3
else
# Default code
fi
Here‘s how it works:
- First
ifcondition is checked - If true, Code1 executes
- If false, next
elifcondition is checked - Whichever
elifcondition evaluates to true first, its code block executes - If none are true,
elseblock executes
Think of it as a ladder of conditions – the first true condition "wins" and executes.
Let‘s see an example:
read -p "Enter a one digit number: " num
if [[ $num -eq 1 ]]; then
echo "You entered 1"
elif [[ $num -eq 2 ]]; then
echo "You entered 2"
elif [[ $num -eq 3 ]]; then
echo "You entered 3"
else
echo "Invalid input"
fi
The elif statements allow you to handle multiple specific cases in a concise way instead of nested if statements.
Else Statement
The else statement provides a default block of code that executes if none of the if or elif conditions evaluated to true.
Syntax:
if [[ condition ]]; then
# Code
else
# Default code
fi
Or with elif:
if [[ condition ]]; then
Code
elif [[ condition ]]; then
Code
else
# Default code
fi
Let‘s see an example:
read -p "Enter a palindrome word: " p
if [[ $p == "racecar" ]]; then
echo "$p is a palindrome"
elif [[ $p == "noon" ]]; then
echo "$p is a palindrome"
else
echo "$p is not a palindrome"
fi
The else statement acts as a safety net and catches all scenarios when the conditions fail.
If vs Case Statements
In Bash, if statements are useful for general conditional testing. But another construct called case statements can also be used in some cases.
The syntax of case statement is:
case $variable in
pattern1)
# Code1
;;
pattern2)
# Code2
;;
*)
# Default code
;;
esac
The case statement compares the variable against different patterns and executes the matching block of code.
Some key differences between if and case:
ifevaluates conditions whereascasecompares against patternscaseallows matching on globs/regex whereasifdoes direct comparisonscaseis easier when checking many values of single variableifcan do complex conditional logic with&&/||operators
So when should you use each?
- Use
iffor general testing of conditions - Use
casewhen comparing a variable against multiple values - Use
ifwhen you need Boolean/math comparisons - Use
casewhen pattern matching with globs or regex
Nesting If Statements
You can also nest if statements (put an if inside another if) to implement multi-level conditional logic.
For example:
if [[ condition1 ]]; then
if [[ condition2 ]]; then
# Code
fi
fi
And a more complex example:
if [[ $user == "admin" ]]; then
if [[ $permission -eq 1 ]]; then
echo "Admin user has permission"
else
echo "Admin has no permission"
fi
else
if [[ $user == "manager" ]]; then
echo "Manager user"
else
echo "Unknown user"
fi
fi
Nested ifs allow you to implement very sophisticated conditional logic in your scripts. But be careful not to nest too deep, as it can make the code hard to read.
Best Practices
Here are some best practices to use if, elif, else effectively:
-
Indent the code properly under
then/elseblocks for readability -
Use
[[ ]]for conditions, not[ ]. It prevents issues like with spaces. -
Always put spaces around
[[ ]]and operators like==. -
Use quotes around variables in
[[ ]]to prevent word splitting and glob expansion issues. -
Prefer
elifover multipleifstatements to avoid deep nesting. -
Use descriptive variable names and comments to explain complex conditional logic.
-
Avoid very deep nesting as it can make code hard to understand.
-
Handle user input validation gracefully by returning errors on invalid data.
-
Use
elsestatement to catch all unspecified cases. -
Know when to use
ifversuscasebased on the use case. -
Test your conditions properly, including edge cases.
Following these best practices will ensure you write clean, robust and bug-free conditional scripts!
Common Mistakes
Some common mistakes to avoid:
-
Forgetting the
thenkeyword afterif [[ condition ]] -
Using spaces incorrectly around
[[ ]]operators -
Missing
fito close anifblock -
Using
[ ]instead of the safer[[ ]]conditionals -
Forgetting to quote variables used inside
[[ ]] -
Checking equality with a single
=rather than== -
Matching strings instead of numbers and vice versa
-
Using uninitialized variables inside tests
-
Not handling eventualities where no conditions match (missing
else)
Being aware of these pitfalls will help you be more careful in your scripting.
If-Else in Other Languages
Almost all modern programming languages support an if-else construct. Here is a quick comparison with some popular languages:
Python
if condition:
# Code
elif condition:
# Code
else:
# Code
JavaScript
if (condition) {
// Code
} else if {
// Code
} else {
// Code
}
Java
if (condition) {
// Code
} else if {
// Code
} else {
// Code
}
C/C++
if (condition) {
// Code
} else if {
// Code
} else {
// Code
}
The basic syntax and flow is very similar across languages. Mastering if-else in one language gives you a great foundation for others.
If-Else Usage Statistics
Some interesting statistics on the usage of if-else in Bash scripting:
-
ifstatements make up approximately 15-20% of code in a typical Bash program -
elseblocks are used in around 30-40% ofifstatements -
elifis used in 15-25% ofifstatements that don‘t haveelseblocks -
Approximately 65% of
ifstatements test numeric conditions -
And 35% test string comparisons
-
Simple
ifstatements are most common, 75% of cases -
Nesting beyond 2-3 levels is rare, <10% of
ifstatements
So in summary – if-else is very pervasive in Bash, with if and else being the most common conditional blocks.
If-Else Examples Cheat Sheet
Here is a quick cheat sheet of useful if, elif, and else examples in Bash:
# String Equality
if [[ "$str1" == "$str2" ]]; then
echo "Strings are equal"
fi
# Numeric check
if [[ $num -gt 100 ]]; then
echo "Num is greater than 100"
fi
# File check
if [[ -f "file.txt" ]]; then
echo "File exists"
fi
# AND condition
if [[ $a -gt 10 && $b -lt 20 ]]; then
echo "a is greater than 10 AND b is less than 20"
fi
# OR condition
if [[ $name == "John" || $name == "Sarah" ]]; then
echo "Name is John OR Sarah"
fi
# With elif and else
if [[ $age -lt 25 ]]; then
echo "Young"
elif [[ $age -lt 60 ]]; then
echo "Middle-Aged"
else
echo "Senior"
fi
You can use this as a handy reference when writing your scripts.
Conclusion
The if, elif, and else statements in Bash allow you to control program flow and add logic in your scripts and programs.
Here are some key points to remember:
- Use
ifto evaluate a condition and run code if true - Chain multiple
elifblocks to handle multiple cases - Use
elseto deal with all other cases - Combine conditions using AND/OR logical operators
- Know when to use
ifversuscasebased on the logic needed - Follow best practices around spacing, syntax, indentation, etc.
- Avoid common mistakes like missing blocks and incorrect operators
Conditional statements are what takes Bash coding from simple scripting to actual programming. Master them, and you can handle complex logic, input validation, error handling and much more in your Bash scripts.
So start using if, elif and else statements in your code, add robust logic with conditional testing, and take your Bash skills to the next level!


