Master Bash if, else, and elif Statements (Beginner Friendly 2025)

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, and elif 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

OperatorMeaning
-eqEqual to (numbers)
-neNot equal to
-ltLess than
-leLess than or equal
-gtGreater than
-geGreater than or equal

String Comparison Operators

OperatorMeaning
=Equal
!=Not equal
<Less than (in ASCII order)
>Greater than (ASCII)
-zString is empty
-nString 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

  1. Always use quotes around variables: "${var}" to avoid bugs.
  2. Spaces matter: [ "$a" = "$b" ] (correct) vs ["$a"="$b"] (wrong).
  3. 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

KeywordUse Case
ifStart a condition
elseAlternative if condition is false
elifCheck another condition if the first fails
fiEnd the if block

Practice Ideas

  1. Script to check if a user exists on your system.
  2. Temperature-based clothing suggestion script.
  3. Script that suggests meals based on time (morning, noon, evening).
  4. 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 

Special thanks to @mr-raj for contributing to this article on Embedded Prep

Leave a Reply

Your email address will not be published. Required fields are marked *