
Bash Scripting: Mastering Conditional Statements
Unlocking Logic Flow in Shell Scripts
In Bash scripting, conditional statements are essential for decision-making. They allow your script to behave differently depending on specific conditions—like checking if a file exists, comparing numbers, or evaluating user input.
What Are Conditional Statements in Bash?
Conditional statements in Bash allow you to control the flow of your script based on whether a condition is true or false.
In simple terms:
“If something is true, do this; otherwise, do that.”
Types of Conditional Statements in Bash
if statement
if…else statement
if…elif…else ladder
Nested if statements
case statement
if Statement
Syntax:
if [ condition ]; then
#commands
fi
Example:
if [ -f “file.txt” ]; then
echo “file.txt exists.”
fi
This checks if the file file.txt exists.
- if…else Statement
Syntax:
if [ condition ]; then
#if true
else
#if false
fi
Example:
if [ “$USER” = “admin” ]; then
echo “Welcome, admin.”
else
echo “Access denied.”
fi
- if…elif…else Ladder
Use elif (short for else if) to check multiple conditions.
Syntax:
if [ condition1 ]; then
#do this
elif [ condition2 ]; then
#do that
else
#do something else
fi
Example:
if [ $score -gt 90 ]; then
echo “Grade: A”
elif [ $score -gt 75 ]; then
echo “Grade: B”
else
echo “Grade: C”
fi
- Nested if Statements
You can place an if inside another if to test multiple levels of logic.
Example:
if [ “$user” = “admin” ]; then
if [ “$password” = “secret” ]; then
echo “Access granted.”
else
echo “Wrong password.”
fi
else
echo “Unknown user.”
fi
- case Statement (Alternative to if-elif)
Useful when you need to compare a variable against multiple values.
Syntax:
case “$variable” in
pattern1)
#commands
;;
pattern2)
#commands
;;
*)
#default
;;
esac
Example:
read -p “Enter your role: ” role
case “$role” in
admin)
echo “Welcome, admin.” ;;
guest)
echo “Welcome, guest.” ;;
*)
echo “Unknown role.” ;;
esac
Common Conditional Operators
Operator Description
-eq - Equal (integers)
-ne - Not equal
-gt - Greater than
-lt - Less than
-ge - Greater than or equal to
-le - Less than or equal to
= - Equal (strings)
!= - Not equal (strings)
-z - String is empty
-n - String is not empty
-f - File exists
-d - Directory exists
-e - File or directory exists
Real-World Use Cases
- Automating Backups
You might want to check if a directory exists before running a backup:
if [ -d “/backup” ]; then
cp -r /important/files/* /backup/
else
echo “Backup directory not found! Creating now…”
mkdir /backup
cp -r /important/files/* /backup/
fi
Use case: Ensures your script doesn’t fail if the backup directory is missing.
- Checking Network Connectivity
Automate checking if a server is reachable before attempting deployment:
if ping -c 1 server.example.com &> /dev/null; then
echo “Server is up, deploying updates…”
#deploy code here
else
echo “Server unreachable, aborting deployment.”
fi
Use case: Prevents wasting time trying to deploy to an offline server.
- Installing Missing Packages
Install software only if it isn’t already installed:
if ! command -v curl &> /dev/null; then
echo “curl not found, installing…”
sudo apt install -y curl
else
echo “curl is already installed.”
fi
Use case: Great for setup scripts on new servers or developer environments.
- Conditional Logging
Log errors to a file only if an operation fails:
if ! cp source.txt /destination/; then
echo “$(date): Failed to copy file.” >> /var/log/script_errors.log
else
echo “File copied successfully.”
fi
Use case: Build automated error logs for debugging production scripts.
- Automated User Management
Check if a user exists before adding them to the system:
username=“deploy”
if id “$username” &>/dev/null; then
echo “User $username already exists.”
else
sudo useradd “$username”
echo “User $username created.”
fi
Use case: Maintain scripts for setting up servers or adding new team members reliably.
- Interactive Installers
Prompt users during setup scripts:
read -p “Do you want to install optional tools? (y/n): ” answer
if [[ “$answer” == “y” || “$answer” == “Y” ]]; then
echo “Installing optional tools…”
#installation commands here
else
echo “Skipping optional tools.”
fi
Use case: Create interactive installers for custom software.
- Automated Disk Space Checks
Notify or act if disk usage exceeds a threshold:
threshold=90
usage=$(df / | grep / | awk ‘{ print $5 }’ | sed ‘s/%//g’)
if [ “$usage” -gt “$threshold” ]; then
echo “Warning: Disk usage above ${threshold}%!”
optional: send email or free up space
else
echo “Disk usage is within safe limits.”
fi
Use case: Avoid outages or performance issues due to full disks.
- Choose Different Configs Based on Hostname
Deploy different configurations automatically depending on the server:
hostname=$(hostname)
if [[ “$hostname” == “web-server-1” ]]; then
config=“web1.conf”
elif [[ “$hostname” == “web-server-2” ]]; then
config=“web2.conf”
else
config=“default.conf”
fi
echo “Using config: $config”
Use case: Run the same script across multiple servers with tailored configurations.
Tips and Best Practices
✅ Always quote variables (“$var”) to avoid word splitting errors.
✅ Use [[ … ]] instead of [ … ] for advanced expressions and string comparison.
✅ Test your script for empty input, file permissions, and invalid values.
✅ Combine conditions using && (AND) or || (OR):
if [[ $age -ge 18 && $citizen = “yes” ]]; then
echo “Eligible to vote.”
fi