How to use if elif else in bash
Categories:
Mastering Conditional Logic: If, Elif, and Else in Bash Scripting

Learn how to implement robust conditional logic in your Bash scripts using if
, elif
, and else
statements. This guide covers syntax, common comparisons, and best practices for effective decision-making.
Conditional statements are fundamental to any programming or scripting language, allowing your code to make decisions and execute different blocks of commands based on specific conditions. In Bash, the if
, elif
(else if), and else
constructs provide powerful tools for controlling script flow. Understanding how to use these effectively is crucial for writing dynamic and responsive shell scripts.
The Basic if
Statement
The simplest form of conditional logic in Bash is the if
statement. It evaluates a condition, and if that condition is true, it executes a block of commands. If the condition is false, the block is skipped. The condition is typically an expression that returns an exit status of 0 (true) or non-zero (false).
# Basic if statement syntax
if [ condition ]; then
# Commands to execute if condition is true
echo "Condition is true!"
fi
# Example: Check if a number is greater than 10
NUM=15
if [ "$NUM" -gt 10 ]; then
echo "$NUM is greater than 10."
fi
# Example: Check if a file exists
FILE="/etc/passwd"
if [ -f "$FILE" ]; then
echo "File '$FILE' exists."
fi
Basic if
statement syntax and examples.
[
]
or [[
]]
to prevent word splitting and globbing issues, especially when dealing with file paths or strings that might contain spaces.Adding Alternatives with else
The else
statement provides an alternative block of commands to execute when the if
condition evaluates to false. This allows you to define behavior for both outcomes of a single condition.
# if-else statement syntax
if [ condition ]; then
# Commands if condition is true
echo "Condition is true."
else
# Commands if condition is false
echo "Condition is false."
fi
# Example: Check if a number is even or odd
NUM=7
if (( NUM % 2 == 0 )); then
echo "$NUM is an even number."
else
echo "$NUM is an odd number."
fi
Using if-else
for two-way decision making.
Handling Multiple Conditions with elif
When you need to check multiple distinct conditions sequentially, elif
(short for 'else if') comes into play. It allows you to chain several conditions together. The script will execute the command block of the first if
or elif
condition that evaluates to true, and then exit the entire if
block. If none of the if
or elif
conditions are true, the else
block (if present) will be executed.
# if-elif-else statement syntax
if [ condition1 ]; then
# Commands if condition1 is true
elif [ condition2 ]; then
# Commands if condition2 is true
elif [ condition3 ]; then
# Commands if condition3 is true
else
# Commands if none of the above conditions are true
fi
# Example: Grade calculator
SCORE=85
if [ "$SCORE" -ge 90 ]; then
echo "Grade: A"
elif [ "$SCORE" -ge 80 ]; then
echo "Grade: B"
elif [ "$SCORE" -ge 70 ]; then
echo "Grade: C"
else
echo "Grade: F"
fi
Using if-elif-else
for multi-way decision making.
flowchart TD A[Start] A --> B{Condition 1?} B -- True --> C[Execute Block 1] B -- False --> D{Condition 2?} D -- True --> E[Execute Block 2] D -- False --> F{Condition 3?} F -- True --> G[Execute Block 3] F -- False --> H[Execute Else Block] C --> I[End] E --> I G --> I H --> I
Flowchart illustrating the logic of an if-elif-else
structure.
Common Test Operators and Best Practices
Bash offers various operators for testing conditions within if
statements. You can use [
]
(test command), [[
]]
(new test command), or ((
))
(arithmetic evaluation).
File Test Operators:
-f FILE
: True if FILE exists and is a regular file.-d DIR
: True if DIR exists and is a directory.-e PATH
: True if PATH exists (file or directory).-r FILE
: True if FILE exists and is readable.-w FILE
: True if FILE exists and is writable.-x FILE
: True if FILE exists and is executable.
String Test Operators:
"STRING1" = "STRING2"
: True if the strings are equal."STRING1" != "STRING2"
: True if the strings are not equal.-z "STRING"
: True if the string is empty.-n "STRING"
: True if the string is not empty.
Integer Test Operators:
NUM1 -eq NUM2
: True if NUM1 is equal to NUM2.NUM1 -ne NUM2
: True if NUM1 is not equal to NUM2.NUM1 -gt NUM2
: True if NUM1 is greater than NUM2.NUM1 -ge NUM2
: True if NUM1 is greater than or equal to NUM2.NUM1 -lt NUM2
: True if NUM1 is less than NUM2.NUM1 -le NUM2
: True if NUM1 is less than or equal to NUM2.
For arithmetic comparisons, (( ))
is generally preferred as it supports standard C-style operators (==
, !=
, >
, <
, >=
, <=
) and doesn't require quoting variables.
# Using [[ ... ]] for string and pattern matching
NAME="Alice"
if [[ "$NAME" == "Alice" ]]; then
echo "Hello, Alice!"
fi
# Using (( ... )) for arithmetic comparisons
AGE=25
if (( AGE >= 18 && AGE <= 65 )); then
echo "You are in the working age range."
fi
# Combining conditions with logical operators
# -a for AND, -o for OR within [ ]
# && for AND, || for OR within [[ ]] or (( ))
USER="admin"
if [ -f "/var/log/syslog" -a "$USER" == "admin" ]; then
echo "Admin user and syslog exists."
fi
if [[ -d "/tmp" && "$USER" != "guest" ]]; then
echo "/tmp exists and user is not guest."
fi
Examples of different test operators and combining conditions.
if [ condition ]
requires spaces around the brackets and operators. Forgetting them (e.g., [condition]
) will lead to syntax errors.