Bash if, else, and elif Statements : Are you ready to level up your shell scripting skills in 2025? This beginner-friendly guide is your one-stop solution to understanding decision-making in Bash using if
, else
, and elif
statements.
In this hands-on tutorial, you’ll explore the power of conditional logic in Bash scripting — the key to writing smarter, more dynamic scripts. We’ll walk you through:
- The basic syntax of
if
,else
, andelif
blocks - Real-world use cases and examples you can actually use
- Common mistakes beginners make and how to avoid them
- Tips to make your conditional statements clean, efficient, and readable
- Interactive practice scenarios to solidify your understanding
Whether you’re automating tasks, building simple CLI tools, or just exploring Bash, mastering these control structures will help you script with confidence and precision.
No prior experience? No worries. By the end of this tutorial, you’ll go from “what does elif
even mean?” to confidently writing conditional logic like a pro.
Let’s dive in and make your Bash scripts smarter in 2025!
What Are Conditional Statements in Bash if , else?
Conditional statements allow your script to make decisions. Bash checks if a condition is true or false, and runs different code based on that.
Basic Syntax of if
if [ condition ]
then
# commands to run if condition is true
fi
Example 1: Check If a File Exists
#!/bin/bash
filename="myfile.txt"
if [ -f "$filename" ]
then
echo "✅ File '$filename' exists."
else
echo "❌ File '$filename' does not exist."
fi
Breakdown:
-f
checks if the file exists and is a regular file.- If true, it prints the success message.
- If false, the
else
part executes.
Using elif
for Multiple Conditions
#!/bin/bash
number=10
if [ $number -lt 5 ]
then
echo "Number is less than 5"
elif [ $number -eq 10 ]
then
echo "Number is exactly 10"
else
echo "Number is greater than 5 but not 10"
fi
Explanation:
-lt
= less than-eq
= equal to
Case 1: Disk Space Check
#!/bin/bash
disk_usage=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ $disk_usage -gt 90 ]
then
echo "⚠️ Warning: Disk usage is above 90%!"
elif [ $disk_usage -gt 70 ]
then
echo "🟠 Caution: Disk usage is above 70%."
else
echo "✅ Disk usage is under control."
fi
This can help in setting up server monitoring scripts.
Comparison Operators in Bash
Operator | Meaning |
---|---|
-eq | Equal to (numbers) |
-ne | Not equal to |
-lt | Less than |
-le | Less than or equal |
-gt | Greater than |
-ge | Greater than or equal |
String Comparison Operators
Operator | Meaning |
---|---|
= | Equal |
!= | Not equal |
< | Less than (in ASCII order) |
> | Greater than (ASCII) |
-z | String is empty |
-n | String is NOT empty |
Example:
name="Nish"
if [ "$name" = "Nish" ]
then
echo "Hello Nish!"
fi
Case 2: Weather-Based Message (Simulated)
#!/bin/bash
weather="rainy"
if [ "$weather" = "sunny" ]
then
echo "Go for a walk!"
elif [ "$weather" = "rainy" ]
then
echo "Carry an umbrella ☔"
else
echo "Check the forecast!"
fi
Tips for Writing if
Statements in Bash
- Always use quotes around variables:
"${var}"
to avoid bugs. - Spaces matter:
[ "$a" = "$b" ]
(correct) vs["$a"="$b"]
(wrong). - Use
[[ ]]
if you’re doing complex conditionals or pattern matching.
Nested if
Statements
#!/bin/bash
age=20
country="India"
if [ $age -ge 18 ]
then
if [ "$country" = "India" ]
then
echo "You can vote in India!"
else
echo "You are eligible, but not in India."
fi
else
echo "You're too young to vote."
fi
Case 3: Login Simulation
#!/bin/bash
username="admin"
password="secret123"
read -p "Enter username: " u
read -sp "Enter password: " p
echo
if [ "$u" = "$username" ] && [ "$p" = "$password" ]
then
echo "✅ Login successful!"
else
echo "❌ Login failed!"
fi
BONUS: Using case
for Clean Multiple Choices
Sometimes if-elif
becomes messy. case
helps:
#!/bin/bash
read -p "Enter your choice (start/stop/restart): " action
case "$action" in
start) echo "Starting service...";;
stop) echo "Stopping service...";;
restart) echo "Restarting service...";;
*) echo "Invalid choice.";;
esac
Summary
Keyword | Use Case |
---|---|
if | Start a condition |
else | Alternative if condition is false |
elif | Check another condition if the first fails |
fi | End the if block |
Practice Ideas
- Script to check if a user exists on your system.
- Temperature-based clothing suggestion script.
- Script that suggests meals based on time (morning, noon, evening).
- File backup script if size exceeds certain MB.
Frequently Asked Questions (FAQ)
Q1. What is the purpose of if
, else
, and elif
in Bash?
A: These are conditional statements that help your script make decisions. You can use them to run different blocks of code based on specific conditions, like checking if a file exists or comparing numbers.
Q2. I’m completely new to Bash. Can I still follow this tutorial?
A: Absolutely! This tutorial is designed with beginners in mind. We start from the very basics and gradually introduce more complex examples to help you build confidence step by step.
Q3. What’s the difference between elif
and else
?
A: elif
(short for “else if”) lets you test additional conditions after an if
statement. else
runs only if none of the previous conditions are true. Think of elif
as a second chance to test more logic before defaulting to else
.
Q4. Can I use these statements in loops or functions?
A: Yes! if
, else
, and elif
can be used inside loops and functions to add more logic and control flow to your scripts.
Q5. How can I test my conditional Bash scripts safely?
A: We recommend using the bash -x yourscript.sh
command to debug and trace your script line by line. It helps you understand how your logic is executed.
Q6. What should I do if my script gives a syntax error?
A: Syntax errors are often caused by missing then
, incorrect spacing, or forgetting to close blocks with fi
. Don’t worry — we’ll show you the most common errors and how to fix them in the tutorial.
Q7. Will this tutorial cover real examples?
A: Yes! We include practical examples like checking user input, file existence, and numeric comparisons to help you apply what you learn in real-world scripts.
Q8. Is this relevant for Linux users only?
A: Bash is most commonly used in Linux and macOS, but Windows users can also follow along using WSL (Windows Subsystem for Linux) or Git Bash.
You can also Visit other tutorials of Embedded Prep
- What is eMMC (Embedded MultiMediaCard) memory ?
- Top 30+ I2C Interview Questions
- Bit Manipulation Interview Questions
- Structure and Union in c
- Little Endian vs. Big Endian: A Complete Guide
- Merge sort algorithm
Special thanks to @mr-raj for contributing to this article on Embedded Prep
Leave a Reply