If Statement in Bash

The if statement is a primary and powerful control structure that creates optimized decision-making logic and manages the scripts’ flow. With the help of many conditional operators like comparison operators, logical operators, file test operators, etc, an ‘if’ statement can easily make your scripts capable of responding to different scenarios. So, let’s get started exploring the basics of Bash if statement with the following guide.

How ‘if’ Statement Works?

The if statement is a fundamental conditional structure that is used to control and make decisions based on specific conditions. This control statement checks whether a condition is true or false. If a particular condition is satisfied, the if statement executes a given code block. But if the condition is false, it doesn’t execute any command.

Flow diagram of 'if' statement in Bash

Syntax of if Statement in Bash

Here are 3 different syntaxes of ‘if statement’ in Bash script:

1. Single Square Brackets [ ] or “test” Command

This syntax supports three types of conditional checks such as numeric conditions, string-based conditions, and file-based conditions.

if [ condition ]; then
#Command to execute if it satisfies the condition
fi

Or,

if test condition; then
#Command to execute if it satisfies the condition
fi

Note: Make sure to insert the spaces between the brackets [ ] at the first line and a semicolon at the end of the brackets.

2. Double Square Brackets [[ ]]

The double square brackets [[ ]] work similarly to the single square brackets [ ]. However, [[ ]] provides enhanced functionality compared to [ ].

if [[ condition ]]; then
#Command to execute if it satisfies the condition
fi

3. Double Parentheses (( ))

Using double parentheses (( )) syntax is useful for number-based conditions or arithmetic calculations.

if (( condition )); then
#Command to execute if it satisfies the condition
fi

3 Different Cases of ‘If Statement’ in Bash

In Bash scripting, ‘if’ is a versatile conditional statement that contains many options (conditional operators) to perform a specific task. Here, in the following section, I’m going to describe how you can avail the if statement with a single condition, multiple conditions, and nested if conditions to compare strings and integers.

Case 1: If Statement with Single Condition

In Bash, an if statement with a single condition is a very basic interpretation. Using a conditional operator within an if statement is enough to imply a single conditional check.

Here’s an example of Bash ‘if statement’ with a single condition:

#!/bin/bash

number=2

#if statement with a single condition
if [ $number -lt 5 ]; then
    echo "The variable is less than 5."
fi
EXPLANATION

In #!/bin/bash, ‘#!’ is called Shebang’ or ‘Hashbang. First, the script initializes a variable number. Then, using the if statement, it checks if the inserted number is less than 5. Finally, If the condition is satisfied, the script employs the echo command to display the output.

Using if statement with single condition

From the image, you can see that a single condition is satisfied successfully using the if conditional statement.

Case 2: If Statement with Multiple Conditions

When you have multiple conditions to consider, you can use the ‘if statement’ with no doubt. You can not only do some code block execution when multiple conditions are satisfied but also execute any command if one of the several conditions is satisfied.

To utilize multiple conditions in a single “If Statement”, you can append the logical operators (&& or ||) between each condition like the following:

#!/bin/bash

echo "Enter username"
read username
echo "Enter password"
read password
if [[ "$username" == "X" && "$password" == "123" ]]; then
echo "Successfully logged in."
fi
EXPLANATION

Here, the script prompts the user for a username and password and then checks if two conditions are true using the if statement. Finally, it echoes the output message if both conditions are satisfied.

Using if statement with multiple conditions

The above image depicts that multiple conditions i.e. two conditions can be satisfied at a time using the if conditional statement.

Case 3: Nested If Statement

Sometimes, you may feel that you need ‘if statements’ as many as possible in your scripts. In that case, you can use an if statement inside another if statement which is called nested if. This performs a nested conditional check. Here’s a simple interpretation for you:

#!/bin/bash

number=60

#Nested if statements
if [ $number -gt 50 ]
then
echo "The number is greater than 50."
if (( $number % 2 == 0 ))
then
echo "It's an even number."
fi
fi
EXPLANATION

First, the script initializes a variable number and then checks if the value of the variable is greater than 50. If the condition is true, then it enters the nested if that is inside the first ‘if’ block and checks if the number is an even number. Finally, the script displays the outputs for each true condition employing the echo command.

Using nested if statement

From the above image, you can see that multiple conditions can be verified by using the nested if conditional statement.

Practical Examples Using ‘if’ Statement in Bash

If statements serve a variety of purposes in Bash scripting. It is so versatile that you can use it to perform different conditional operations over strings, numbers, functions, arrays, etc, and make decisions based on various conditions.

Here are 3 practical examples of Bash if statements in the following section:

1. Checking a File’s Existence Using If Statement

To check if a file exists and is a regular file, use the -f option within a test expression in the if conditional statement. Follow the script below to check a file’s existence:

#!/bin/bash

file_name="file1.txt"

#Checking if the file exists and is a regular file
if [ -f "$file_name" ]; then
echo "$file_name exists and is a regular file."
fi

EXPLANATION

Here, the syntax if [ -f "$file_name" ] checks whether the file file1.txt exists in the system and is a regular file. If the condition is satisfied, it executes a true expression with an output message. Otherwise, it returns nothing.

Checking a file's existence using 'if' statement

From the above image, you can see that the file file1.txt exists in my system and it is a regular file.

2. Determining If a Number is Even Using If Statement

An even number is defined as an integer that is divisible by 2 meaning that there is no remainder. The modulo (%) operator returns the remainder of a division operation and helps in determining if a number is even.

Here’s how you can determine if a number is even in Bash:

#!/bin/bash

#Checking if a number is even
is_even_number() {
if [ $(( $1 % 2 )) -eq 0 ]; then
echo "$1 is even."
fi
}

is_even_number 8
is_even_number 11

EXPLANATION

Here, the syntax if [ $(( $1 % 2 )) -eq 0 ] inside the function checks whether the remainder of the number divided by 2 is equal to 0 where $1 represents the first argument passed to the function. If the remainder is equal to 0, the number is even and the script prints an output message. Otherwise, it indicates the number is odd and the script prints nothing.

Checking if a number is even using 'if' statement

In the above image, you can see that among the inserted numbers 8 and 11, 8 is even.

3. Handling Floating-point Comparison Using ‘If Statement’ in Bash

Sometimes, there can be slightly different floating-point numbers that need to be handled in bash scripts. In this effort, a common approach is to use the if statement with an external command bc (Basic Calculator).

Here is an example where the script does a comparison between floating-point numbers:

#!/bin/bash

#Comparing floating-point numbers in Bash
variable1=5.95
variable2=5.951

#Defining a value of tolerance
tolerance=0.01

#Calculating the difference between the two floating-point numbers
difference=$(bc -l <<< "$variable1 - $variable2")

#Checking if the difference is less than the tolerance value
if (( $(bc -l <<< "$difference <= $tolerance") )); then
    echo "The numbers are almost equal."
fi
EXPLANATION

Firstly, The script starts with two variables with two different values. Then, it defines a variable tolerance with a value of 0.01. After that, the script uses the bc command to check the difference between variable1 and variable2. Now, it checks if the difference between the variables is less than or equal to the tolerance value using the if statement and displays an output when the condition is true by using the echo command.

Handling floating-point numbers using 'if' statement

From the image, you can see that using the if statement with the help of the bc command can help compare the floating-point numbers resulting in ‘The numbers are almost equal’ here.

Conclusion

Wrapping up, the ‘if statement’ is an essential element in Bash that can streamline and evaluate your scripts by making effective decisions depending on different conditions.

People Also Ask

How to use if statement in Bash?

To use an if statement in Bash, follow this general syntax:

if [ condition ]; then
# code to execute if condition is true
else
# code to execute if condition is false
fi

Replace [ condition ] with your actual condition, and replace the code inside the then and else blocks with the actions you want to take based on the condition.

Can I Use Regular Expressions in ‘if’ Statements in Bash?

Yes, you can use regular expressions with the double square brackets construct [[ ]]’ in the ‘if’ statements in Bash.

Is There a Limit to the Number of Conditions That Can Be Checked in a Single ‘if’ Statement in Bash?

No, there’s no specific limit to the number of conditions that can be checked in a single if statement in Bash. But remember that using a lot of ‘if’ conditions can make your code more complex.

Can I Handle Errors With ‘if’ Statements in Bash?

Yes, you can handle errors with ‘if’ statements in Bash by checking the exit status of commands. Every command in Bash returns an exit status, which indicates whether the command was successful (exit status 0) or encountered an error (non-zero exit status). You can use this in ‘if’ statements to control the flow of your script based on command execution success or failure.

Can I Use Arithmetic Operations Directly Within an ‘if’ Statement Condition in Bash Script?

Yes, you can use arithmetic operations directly within an ‘if’ statement condition in a Bash script. Bash supports arithmetic evaluation using the $((…)) syntax. For example, you can compare two numeric values like this: if [ "$a" -eq "$b" ]; then ... fi, where -eq is the equality operator. Arithmetic operations can be performed directly inside the condition, such as if [ "$((a + b))" -gt "10" ]; then ... fi, where the sum of a and b is compared to 10.

What is Bash Inline if?

Bash inline if means executing a conditional check in a single coded line. Using the ternary operator is a concise way to express the conditional statement in a single line. It follows the syntax condition && true_command || false_command. If the condition is true, the true_command is executed; otherwise, the false_command is executed. This construct is particularly useful when you want to assign a value or execute a command based on a simple condition without the need for a full-fledged if-else statement.

Related Articles


<< Go Back to Bash Conditional Statements | Bash Scripting Tutorial

4.8/5 - (19 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment