If-elif-else Statements in Bash
Bash scripting is powerful but can be confusing for newcomers, especially when it comes to conditional statements. One common pitfall is incorrectly using comparison operators, which leads to unexpected behavior in your scripts.
The Problem: Incorrect Comparison Operators
The core issue in the original question stems from using the wrong comparison operator. In bash, -eq
is specifically for numeric comparisons, not string comparisons.
# This will NOT work as expected for string comparison
if [[ $aaa -eq "bbb" ]]; then
echo "bbb"
fi
Solution: Use the Right Operators and Proper Quoting
For string comparisons in bash, you should use =
or ==
(they're equivalent in bash) and always quote your variables to prevent unexpected behavior.
Basic if-elif-else Structure
aaa="xxx"
if [[ "$aaa" == "bbb" ]]; then
echo "bbb"
elif [[ "$aaa" == "ccc" ]]; then
echo "ccc"
else
echo "something else"
fi
Single Bracket Syntax (POSIX-compliant)
if [ "$aaa" = "bbb" ]; then
echo "bbb"
elif [ "$aaa" = "ccc" ]; then
echo "ccc"
else
echo "something else"
fi
TIP
While [[
(double brackets) is generally preferred for bash scripting as it's more robust and feature-rich, [
(single bracket) is POSIX-compliant and works across different shells.
When to Use Different Comparison Operators
# Use = or == with strings
if [[ "$var" == "value" ]]; then
echo "String matches"
fi
# Use -eq, -ne, -lt, -gt with numbers
if [[ $num -eq 10 ]]; then
echo "Number is 10"
fi
Alternative: Case Statements
For multiple string comparisons, a case
statement is often more readable and efficient:
case "$aaa" in
"bbb")
echo "bbb"
;;
"ccc")
echo "ccc"
;;
*)
echo "something else"
;;
esac
Always Quote Variables
Unquoted variables can cause unexpected behavior when they contain spaces or special characters. Always wrap variables in quotes:
# ✅ Correct
if [ "$my_var" = "some value" ]; then
# ❌ Risky - may break with spaces or special characters
if [ $my_var = "some value" ]; then
Common Pitfalls and Solutions
1. Empty Variable Handling
# Safe comparison that handles empty variables
if [ "${aaa:-}" = "bbb" ]; then
echo "bbb"
fi
2. Testing for Empty Strings
# Check if variable is empty
if [ -z "$aaa" ]; then
echo "Variable is empty"
fi
# Check if variable is not empty
if [ -n "$aaa" ]; then
echo "Variable has content"
fi
3. Pattern Matching with Double Brackets
# Pattern matching (only works with [[ ]])
if [[ "$filename" == *.txt ]]; then
echo "Text file detected"
fi
Best Practices Summary
- Use
=
or==
for string comparisons - Use
-eq
,-ne
,-lt
,-gt
for numeric comparisons - Always quote variables to prevent word splitting
- Prefer
[[ ]]
over[ ]
in bash scripts for better features - Consider
case
statements for multiple string comparisons - Test your scripts with various inputs including empty values
By following these guidelines, you'll avoid the common pitfalls of bash conditional statements and write more robust shell scripts.