Getting Started with bash else if: A Beginner’s Guide to Conditional Scripting in Bash
When working with shell scripts in Linux, mastering control flow is key to writing effective and dynamic scripts. One of the most common tools you’ll use in Bash scripting is the conditional if statement. Among its most useful structures is the bash else if (written as elif), which allows for more nuanced, multi-path decision-making.
In this blog, we’ll walk through the fundamentals of using bash else if, explore syntax and examples, and explain how you can apply it in your day-to-day scripting tasks.
Understanding bash else if
The bash else if structure lets you evaluate multiple conditions in sequence. This is particularly helpful when your script needs to make more than a simple true/false decision. Instead of nesting multiple if statements or writing long logic chains, you can streamline your conditions using elif.
The basic syntax is:
if [ condition1 ]; then
# commands for condition1
elif [ condition2 ]; then
# commands for condition2
else
# commands if none of the above conditions match
fi
Each elif acts as a checkpoint. Bash evaluates conditions in order until one is true—then it executes the corresponding block and skips the rest.
A Practical Example
Let’s say you want to write a script to evaluate a user’s age and return different messages based on their input:
!/bin/bash
echo “Enter your age:”
read age
if [ $age -lt 13 ]; then
echo “You are a child.”
elif [ $age -lt 20 ]; then
echo “You are a teenager.”
elif [ $age -lt 65 ]; then
echo “You are an adult.”
else
echo “You are a senior citizen.”
fi
This script uses bash else if logic to guide users through different responses depending on the value of age.
Why Use bash else if?
Using bash else if makes your scripts more readable, maintainable, and scalable. Instead of using nested if blocks or duplicating logic, elif allows you to manage multiple conditions cleanly.
Here are some practical use cases:
- User input validation
- Automating server configurations based on OS version
- Conditional service restarts based on system metrics
Common Tips and Pitfalls
- Use spaces properly:
[ $var -lt 10 ](spaces are required around brackets). - Use
elifinstead of nestedifblocks to avoid unnecessary complexity. - Always close your conditional with
fi, the Bash equivalent ofendif.
Conclusion
The bash else if construct is a vital tool for any Bash script. It allows your scripts to make decisions based on multiple conditions with clarity and control. By mastering bash else if, you’ll write smarter, more adaptable scripts that can handle a wide range of tasks with ease.
To learn more and see additional examples, visit the full guide on Vultr’s documentation.

