When programming, there may be points when you want the computer to do something when a specific situation is true. For such scenarios, you have a programming methodology available called if-else statements. Bash if else statements are used to control the flow of execution based on applying conditions. These will allow you to make decisions, features, commands, or comparisons in your script, whether checking for a file’s existence, validating user inputs, or comparing two values. This article will discuss how if-else statements are used in bash scripting. We will examine syntax more specifically and with real examples supporting how to implement them.
What is Bash Scripting?
Bash scripting helps you automate tasks on Unix-based operating systems (like Linux) using the Bash Shell. This means that you will not need to execute repetitive commands manually, but you can simply write a script file (a set of commands) which can then be executed automatically. Bash scripts are commonly used when doing system administration activities, automating backups, handling files, and keeping track of system resource utilization, among other applications.
In these automated workflows, you will want your script to make decisions based on conditions, like whether or not a file exists, or whether the user input is valid, or if the script should respond differently depending on the system state. This is why if-else statements are so useful; they allow your script to choose between multiple paths, allowing automation to be smarter and more dynamic.
In the next sections, we will understand extensively about Bash if-else statements.
Introduction to If-Else in Bash Scripting
In Bash scripting, much like other programming languages, the if-else statements are a conditional statement that is used as a way to simulate decision-making in computer programming. The if-else statement makes your script “decide” for itself. These statements allow you to run one block of code if a condition evaluates as true, and another block of code if it is false. Because of this, you can guide your script into choosing other paths based on the condition instead of executing commands blindly. This flexibility allows you to create scripts that are more intelligent and up to your judgment. The if-else statements are also one of the most common conditional statements that are used in scripting and coding.
Basic Syntax of Bash If Else Statements
The syntax of Bash if else statements in Scripting is different from the syntax in other programming languages. Though the underlying concept and how it works remain the same. The process is that the condition is checked, and if it is true, the if block is executed; otherwise, the else block is executed.
Syntax:
if [ condition ]
then
# commands to execute if the condition is true
else
# commands to execute if the condition is false
fi
In the above syntax, let us understand each word and symbol, and how you are supposed to write it:
- All if blocks must end with fi (which is simply “if” in reverse), and conditions must be inside square brackets [].
- The then keyword indicates the start of the block that will be executed if the condition holds.
- The else block is optional and is provided only if one wishes to provide alternative commands for when the condition is false.
- It is important to use proper spacing; there needs to be space after [ and a space before ].
You can use Bash if else statements with two or more conditions, as well as with a single condition. Let’s see all the ways you can use if-else statements in bash scripting.
Bash If Statement (Single Condition)
An if statement can be used without any else statement in Bash scripting. You can use this when you only need to act if a particular condition is true, and do nothing otherwise.
Syntax:
if [ condition ]
then
# commands to execute if the condition is true
fi
Example:
#!/bin/bash
num=10
if [ $num -gt 5 ]
then
echo "The number is greater than 5."
fi
Output:
Explanation:
In the above example, the script checks if the variable num is greater than 5. Since this condition is true, the message gets displayed. Also, we have used the numeric comparison operator – gt here for the “greater than” comparison.
If the number you provide, in fact, ends up being less than 5, it will print nothing because you are only using the if statement.
Bash If Else Statement
Using the Bash if else statement is the most common way of using this statement. The addition here is that you can tell the computer what to do in case the if condition returns false.
Let us understand this with the above example. Before num=1, the script printed nothing. Let us print “the number is smaller than 5” when the number is less than 5.
Syntax:
if [ condition ]
then
# commands to execute if the condition is true
else
# commands to execute if the condition is false
fi
Example:
#!/bin/bash
num=1
if [ $num -gt 5 ]
then
echo "The number is greater than 5."
else
echo "The number is smaller than 5."
fi
Output:
Explanation: In this example, the script checks if the number is greater than 5; otherwise, it prints that the number is smaller than 5.
If-Elif-Else Statement in Bash Scripting
Sometimes, you may want to check more than two conditions. In such cases, you can use the elif (else if) clause. It allows you to test multiple conditions one after another. The script will execute the first block where the condition is true, and skip the rest.
Syntax:
if [ condition1 ]
then
# commands to execute if condition1 is true
elif [ condition2 ]
then
# commands to execute if condition2 is true
else
# commands to execute if none of the above conditions are true
fi
Example:
#!/bin/bash
num=5
if [ $num -gt 5 ]
then
echo "The number is greater than 5."
elif [ $num -eq 5 ]
then
echo "The number is equal to 5."
else
echo "The number is smaller than 5."
fi
Output:
Explanation: This script demonstrates conditional logic using an if-elif-else statement. It checks whether the variable num is greater than 5, equal to 5, or smaller than 5, and prints the appropriate message based on the condition that evaluates to true.
Bash If-Else with Multiple Conditions
There may be cases in your Bash scripts where a single condition is insufficient to determine the flow of your script. Being able to use multiple conditions in Bash if else statements allows you to check for more than one condition in your scripts and execute commands accordingly. This puts you in a position to execute different commands in your script based upon more than one variable or state, making the automation smarter and more flexible.
Example:
You might want to check if a user is both root and if a specific service is running, or if a file exists and has the correct permissions. Bash provides logical operators like && (AND) and || (OR) to combine conditions within your if-else statements.
#!/bin/bash
# Example variables
user_id=$EUID
file="example.txt"
service="ssh"
# Check if user is root AND file exists
if [ $user_id -eq 0 ] && [ -f "$file" ]; then
echo "You are root and $file exists."
else
echo "Either you are not root or $file does not exist."
fi
# Check if service is running OR file is writable
if systemctl is-active --quiet $service || [ -w "$file" ]; then
echo "Either $service is running or $file is writable."
else
echo "Neither $service is running nor $file is writable."
fi
Output:
Explanation:
- The first if statement is verifying whether the user is root AND whether example.txt exists. Either the user is not root or the file does not exist, so the if condition is false, which is why the message in the else statement is being displayed.
- The second if statement is verifying whether the SSH service is up and running or whether example.txt is writable. In our environment, systemctl is not present, and the file is not writable, which is the reason for the message in the else statement being displayed.
Nested If Statements in Bash Scripting
At times you may wish to test a condition within another condition. This is where nested if statements in Bash come in; you can place an if statement inside an if statement to create another layer of decision-making.
Example:
#!/bin/bash
num=15
if [ $num -gt 5 ]
then
echo "The number is greater than 5."
if [ $num -gt 10 ]
then
echo "The number is also greater than 10."
fi
else
echo "The number is 5 or smaller."
fi
Output:
Explanation: This script shows nested if statements in action. It first checks if the number is greater than 5, then further checks if it’s greater than 10, printing messages accordingly.
At this point, you have seen how to use the if, if-else, if-elif-else, and nested if statements to control the program’s flow. However, to get useful value checks against our criteria, we will need a file to take a value, a string, or a file, controlled by the conditions. This is done using comparison operators.
Comparison Operators in Bash
In Bash Scripting, the types of comparison operators differ from other programming languages. There are basically three types of comparison operators: Numeric comparisons, String comparisons, and File test operators. As the name suggests, all these types of comparison operators are used with numerics, strings, and files. Let us deep dive and talk about each of them in depth.
1. Numeric Comparisons
When you need to compare numbers in Bash, you are going to have to use numeric comparison operators. Below, we provide you with all the numeric operators in Bash Scripting.
Operator |
Meaning |
-eq |
Equal to |
-ne |
Not equal to |
-lt |
Less than |
-le |
Less than or equal to |
-gt |
Greater than |
-ge |
Greater than or equal to |
Example:
#!/bin/bash
num=7
if [ $num -gt 5 ]
then
echo "The number is greater than 5."
fi
Output:
Explanation: Here, the -gt operator checks if num is greater than 5. Since 7 > 5, the condition evaluates to true. In Bash scripting, numeric comparison operators (-eq
, -ne
, -lt
, -le
, -gt
, -ge
) are used only with numbers.
2. String Comparisons
In Bash Scripting, for string comparisons, you should use string operators such as = and !=. Comparison operators allow you to test for equality, inequality, and even alphabetical ordering among strings. Remember for < and >, you must use [[ … ]] instead of [ … ]. This is because < and > are interpreted as redirection symbols in the single-bracket test.
Operator |
Meaning |
= |
Strings are equal |
!= |
Strings are not equal |
< |
String1 is less than String2 (alphabetical order) |
> |
String1 is greater than String2 (alphabetical order) |
Example:
#!/bin/bash
str1="apple"
str2="banana"
if [[ "$str1" < "$str2" ]]
then
echo "$str1 comes before $str2 alphabetically."
else
echo "$str1 comes after $str2 alphabetically."
fi
Output:
Explanation: The script compares str1 and str2 alphabetically. Since “apple” comes before “banana”, the first condition is true, and the corresponding message is printed.
3. File Test Operators in Bash
The file test operators check properties of files and directories, such as existence, type, and permissions. File test operators are other very useful tools in conditional statements to help you write more robust scripts. These are the file test operators available in Bash scripting.
Operator |
Meaning |
-f filename |
True if the file exists and is a regular file |
-d dirname |
True if the directory exists |
-r filename |
True if the file is readable |
-w filename |
True if the file is writable |
-x filename |
True if the file is executable |
Example:
#!/bin/bash
file="test.txt"
if [ -f "$file" ]
then
echo "The file $file exists."
else
echo "The file $file does not exist."
fi
Output:
Explanation: The -f operator is used to check that the file provided exists and is a normal file. In this script, if test.txt exist, the script prints out a message confirming that the file exists, and if it does not exist, it prints that it does not exist. Since our system does not have a test.txt file in the system, the else block was executed.
Practical Examples of If-Else in Bash
We have talked about all the key concepts you should learn in order to use if else statements in Bash Scripting. Let’s discover some real-world use cases of using conditional statements to help increase your understanding of the concept even further.
1. Check if a User is Root
You might come across instances when working within a script requires root privileges to run certain commands. In those cases, you can use the power of if-else to check the user ID. You can add the code to switch to the root user in order to perform certain actions.
Example:
#!/bin/bash
if [ "$EUID" -ne 0 ]
then
echo "Please run as root."
else
echo "You are running as root."
fi
Output:
Explanation: The script checks the effective user ID (EUID). If it’s not 0 (root), it prompts the user to run the script as root; otherwise, it confirms root access.
2. Validate Command-Line Arguments
Bash if else statements are often used in situations where you need to validate command-line arguments. Scripts frequently take input from users. In this instance, you use if-else to verify that the expected number of arguments is supplied.
Example:
#!/bin/bash
if [ $# -ne 2 ]
then
echo "Usage: $0 <arg1> <arg2>"
exit 1
else
echo "Arguments received: $1 and $2"
fi
Output:
Explanation: This script verifies whether the user has provided exactly two arguments, if not, it displays an error and a message indicating how to use the script. If there are indeed two arguments, it lets the user know what the two arguments were. Finally, the script will wait until the user presses the Enter key to close.
3. Check Disk Space and Send a Warning
When you run out of disk space on your hard drive, it can lead to applications crashing, slowness, and/or loss of data. A good way to avoid these problems is to create a Bash script to monitor disk usage and send a warning when you get near to being out of space. This will allow you to take precautions before the system becomes critical (closing applications that take up space or deleting temporary files, etc). Below is an example of how you could perform this from within a Bash script, using the Bash if else statement.
Example:
#!/bin/bash
disk_usage=$(df / | grep / | awk '{print $5}' | sed 's/%//')
if [ $disk_usage -gt 80 ]
then
echo "Warning: Disk usage is above 80%."
else
echo "Disk usage is under control."
fi
Output:
Explanation: This script checks the disk usage of the root directory by combining several commands. df shows disk space, grep filters the root line, awk ‘{print $5}’ extracts the usage percentage, and sed ‘s/%//’ removes the % for numeric comparison. The if statement then warns if usage exceeds 80%; otherwise, it confirms normal usage.
Since our computer is using more than 80% of disk space, we should close some of the applications and delete some files to free up the space.
Common Mistakes and Debugging Tips
As a beginner, you tend to make these common mistakes when using Bash if else statements:
- Using = vs == in strings: In [ … ], always use = for string comparison. Using == may cause unexpected results in some shells.
- Missing fi: Every if block must be closed with fi. Forgetting it leads to syntax errors.
- Handling spaces in conditions: Ensure there are spaces after [ and before ]. For example, [ $num -gt 5 ] is correct; [ $num -gt 5] will fail.
Best Practices for Writing Bash If Else Statements
Below, we have listed a few best practices that you should follow when using Bash if else statements.
- Code readability and indentation: As a beginner, you should make it a habit of properly indenting if, elif, else, and fi blocks to make scripts easier to read and debug.
- Using [[ … ]] vs [ … ]: There are two kinds of brackets available in Bash, [[…]] and […]. It is suggested to prefer [[ … ]] for complex conditions (like &&, ||, or <, > for strings) to avoid unexpected behavior.
- Using case statements when suitable: For multiple discrete values, case statements are cleaner and more readable than long if-elif-else chains. Always keep in mind not to use if-else statements for more than three conditions.
Conclusion
To conclude this article, we have covered everything related to the Bash if-else statements. We even discussed with examples the various operators of Bash scripting so that you can write accurate code for any decision and data type. By understanding numeric, string, and file comparisons, along with practical examples and common mistakes, you are now equipped to write dynamic, reliable, and efficient Bash scripts for real-world tasks.
Useful Resources:
Bash If Else Statements – FAQs
Q1. How to use if else in Bash script?
You can use if-else in Bash to execute commands based on conditions. Example: if [ condition ]; then commands; else commands; fi
.
Q2. How to use Bash if else with string comparison?
Use = or != to compare strings. Example: if [ "$a" = "$b" ]; then echo "Equal"; else echo "Not equal"; fi
.
Q3. How to use Bash if else with integer comparison?
Use -eq, -ne, -lt, -gt, etc., for integers. Example: if [ $a -eq $b ]; then echo "Equal"; else echo "Not equal"; fi
.
Q4. What is a Bash if else if ladder example?
You can chain multiple conditions using elif. Example: if [ $a -gt $b ]; then echo "a>b"; elif [ $a -lt $b ]; then echo "a.
Q5. How to use Bash if else with logical operators?
Use && (AND) and || (OR) in conditions. Example: if [ $a -gt 5 ] && [ $b -lt 10 ]; then echo "Both true"; fi
.
Q6. What is the difference between if and if else in Bash?
if executes commands only when a condition is true, while if-else provides an alternate command when the condition is false.