How to Use elif in Bash: Syntax and Examples
In bash, use
elif to add multiple conditions in an if statement. It works like "else if" in other languages, letting you check another condition if the previous if or elif was false.Syntax
The elif statement in bash is used between if and else to test additional conditions. The structure is:
if: starts the first conditionelif: tests another condition if the previous was falseelse: runs if all previous conditions are false
bash
if [ condition1 ]; then # commands if condition1 is true elif [ condition2 ]; then # commands if condition2 is true else # commands if none of the above are true fi
Example
This example script checks a number and prints if it is positive, zero, or negative using if, elif, and else.
bash
#!/bin/bash number=5 if [ "$number" -gt 0 ]; then echo "The number is positive" elif [ "$number" -eq 0 ]; then echo "The number is zero" else echo "The number is negative" fi
Output
The number is positive
Common Pitfalls
Common mistakes when using elif include:
- Forgetting spaces around brackets
[ ]which causes syntax errors. - Not closing the
ifblock withfi. - Using
elifwithout a precedingif. - Confusing
elifwithelse if(bash requireselifas one word).
bash
# Wrong: missing spaces if [ "$num" -gt 0 ]; then echo "Positive" elif [ "$num" -eq 0 ]; then echo "Zero" fi # Correct: if [ "$num" -gt 0 ]; then echo "Positive" elif [ "$num" -eq 0 ]; then echo "Zero" fi
Quick Reference
Remember these tips when using elif in bash:
- Always use
elifas one word, notelse if. - Put spaces around brackets and operators.
- Close the entire conditional block with
fi. - You can have multiple
elifblocks to check many conditions.
Key Takeaways
Use
elif to check multiple conditions after an initial if in bash.Always put spaces around brackets and operators in condition tests.
Close your conditional blocks with
fi to avoid syntax errors.elif must be one word; do not write else if.You can use multiple
elif statements to handle many cases.