If Statement in Bash

In Bash scripting, 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 understanding the basics of Bash ‘if’ statement with the following guide.

To download the practice files, click the link below:

What is an ‘If’ Statement in Bash?

The ‘ifstatement is a fundamental conditional structure that is used to control and make decisions in the Bash scripts 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

Basic Syntax >

if [ 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.

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: Single ‘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, I’m giving an example of Bash ‘if’ statement with single condition with proper steps:

  1. Go to Ubuntu Terminal, open a script in the Nano text editor by running the following command:
    nano if_single.sh
    EXPLANATION
    • nano: A text editor.
    • if_single.sh: This is a script. Here, I have named the script ‘if_single.sh’. You can name any of your choices.

    Opening file in Nano text editor

  2. Now, write the following script inside the editor:
    Script (if_single.sh) >
    #!/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. If the condition is satisfied, the script employs the echo command to display the output.

  3. Then, press CTRL+S to save the file & press CTRL+X to exit.
  4. After that, use the command below to make the script executable:
    chmod u+x if_single.sh
    EXPLANATION
    • chmod: Changes the permission of the files and directories.
    • u+x: Adds the executable permission for the user.
    • if_single.sh: The file which you want to make executable.

    Adding executable permission to the script

  5. Finally, run the script by the following command:
    ./if_single.sh

    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: Single ‘If’ Statement With Multiple Conditions in Bash

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 do so, you can append the logical operators (&& or || ) between each condition like the following:

You can follow the Steps of Case 1, to save & make the script executable.

Script (if_multiple.sh) >

#!/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.

Now, run the script by the following command:

./if_multiple.sh

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:

You can follow the Steps of Case 1, to save & make the script executable.

Script (if_nest.sh) >

#!/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. Here, the script displays the outputs for each true condition employing the echo command.

Now, run the script by the following command:

./if_nest.sh

Using nested if statement

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

How to Handle 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, I’m giving an example where the script determines a comparison between floating-point numbers within the specified tolerance threshold (maximum acceptable difference).

You can follow the Steps of Case 1, to save & make the script executable.

Script (float.sh) >

#!/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

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.

Now, run the script by the following command:

./float.sh

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

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 error conditions and responding according to the conditions by using the exit codes.

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 Bash script.

What is Bash Inline if?

Bash inline if means a single coded line that executes an ‘if’ conditional check.

5/5 - (1 vote)
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