Bash Scripting

Bash if…else Statement – Bash Scripting

When it comes to automating tasks on Linux, Bash scripting is an essential skill for both beginners and seasoned sysadmins. Among the most fundamental concepts is conditional decision making, which lets your scripts respond intelligently based on the data or situation at hand. In this comprehensive guide, you’ll discover how to use if statementselse conditions, and elif branches to enhance your Bash scripts for real-world automation scenarios.


What Are Bash Conditional Statements?

Bash conditional statements are logical checks that control your script’s execution flow.
They allow your program to decide what to do next based on given conditions.

Key types:

  • if → Runs a block of code only if a condition is true.
  • elif → Adds additional alternative conditions.
  • else → Executes when none of the above conditions are true.

Basic Bash If Statement Syntax

bashif [ CONDITION ]
then
    # Actions when CONDITION is true
fi

💡 Tip: Use consistent indentation (2–4 spaces) for readability.

Example — Checking if a number is positive:

bash#!/bin/bash
read -p "Enter a number: " num
if [ "$num" -gt 0 ]; then
    echo "The value is positive."
fi

Using If…Else for Dual-Path Logic

If you want to handle both the true and false possibilities, use the else statement.

Syntax:

bashif [ CONDITION ]
then
    # Actions if condition is true
else
    # Actions if condition is false
fi

Example — Age check:

bash#!/bin/bash
read -p "Enter your age: " age
if [ "$age" -ge 18 ]; then
    echo "Access granted."
else
    echo "Access denied. You must be 18 or older."
fi

Advanced: If…Elif…Else for Multiple Conditions

When your script requires more than two possible outcomes, use elif:

bashif [ CONDITION1 ]
then
    # Executes if CONDITION1 is true
elif [ CONDITION2 ]
then
    # Executes if CONDITION2 is true
else
    # Executes if none are true
fi

Example — Grading logic:

bash#!/bin/bash
read -p "Enter a score (0-100): " score
if [ "$score" -ge 90 ]; then
    echo "Grade: A"
elif [ "$score" -ge 75 ]; then
    echo "Grade: B"
else
    echo "Grade: C or lower"
fi

Nesting If Statements

You can check one condition inside another to build more complex decision-making.

bashif [ "$x" -gt "$y" ]; then
    if [ "$x" -gt "$z" ]; then
        echo "$x is largest"
    else
        echo "$z is largest"
    fi
else
    # Nested logic continues
fi

Combining Multiple Conditions

Use logical operators to connect conditions.

AND (&& or -a):

bashif [ "$a" -gt 0 ] && [ "$b" -gt 0 ]; then
    echo "Both numbers are positive."
fi

OR (|| or -o):

bashif [ "$food" = "apple" ] || [ "$food" = "banana" ]; then
    echo "Popular fruit."
fi

Common Bash Test Operators

CategoryOperator / SyntaxDescription
String Operators[ -n "$str" ]True if string is not empty
[ -z "$str" ]True if string is empty
Integer Operators[ "$a" -eq "$b" ]True if integers are equal
[ "$a" -ne "$b" ]True if integers are not equal
[ "$a" -gt "$b" ]True if greater than
[ "$a" -lt "$b" ]True if less than
[ "$a" -ge "$b" ]True if greater or equal
[ "$a" -le "$b" ]True if less or equal
File Test Operators[ -f filename ]File exists and is a regular file
[ -d directory ]Directory exists
[ -e path ]File or directory exists

Pro Bash Tips for Writing Cleaner Scripts

  • Always quote variables: "$VAR"
  • Prefer [[ ... ]] for conditional expressions in modern Bash
  • Add comments to describe your logic
  • Use read -p for interactive prompts
  • Modularize logic with functions for complex scripts

👉 Learn how to write reusable functions here: Bash Functions Explained: Syntax, Examples, and Best Practices

0xSnow

0xSnow is a cybersecurity researcher with a focus on both offensive and defensive security. Working with ethical hacking, threat detection, Linux tools, and adversary simulation, 0xSnow explores vulnerabilities, attack chains, and mitigation strategies. Passionate about OSINT, malware analysis, and red/blue team tactics, 0xSnow shares detailed research, technical walkthroughs, and security tool insights to support the infosec community.

Recent Posts

Install Apache Cassandra on Ubuntu 18.04: NoSQL Setup Guide

Apache Cassandra is a free, open-source NoSQL database designed for high availability and linear scalability with…

16 hours ago

Install Rocket.Chat on Ubuntu 18.04 with Nginx and Let’s Encrypt

Rocket.Chat is a free, open-source team communication platform built with the Meteor framework. It is a…

16 hours ago

Install MySQL on Ubuntu 18.04: Setup, Security, and Root Access

MySQL is the most popular open-source relational database management system. It is fast, reliable, and scales…

16 hours ago

Install Apache on Ubuntu 18.04: Web Server Setup and Config

Apache is the most widely used web server in the world. It is free, open-source, and…

16 hours ago

Install NetBeans IDE on Ubuntu 18.04 with Snap and OpenJDK 8

NetBeans is a free, open-source, cross-platform IDE developed by the Apache Software Foundation. It was one…

17 hours ago

Install Pip on Ubuntu 18.04: Python 3 and Python 2 Setup Guide

Pip is the official package manager for Python and the standard way to install libraries from…

5 days ago