Bash Conditional Statements

In Bash scripting, sometimes you might face a situation when you have to make logical decisions by satisfying certain conditions within your scripts. Conditional statements are the core components here that allow you to make these decisions and control the flow of your Bash scripts based on particular conditional levels. In the following article, you’ll get an in-depth concept of conditional statements in Bash. Let’s explore!

Click the link below to download the practice files:

What is a Conditional Statement in Bash?

A conditional statement is nothing but a form of checking multiple scenarios where inputs are assessed before an execution operation and the results are checked in a true or false format. In Bash, these conditional statements are the most essential tools that help you make decisions in your scripts based on particular conditions and handle errors and bugs within the scripts.

Requirements to Use Conditional Statements in Bash

Before implementing any conditional statement effectively, you must have a good understanding of the test commands and conditional test operators. However, before going through all the types of conditional statements available in Bash, you need to know how to append functional test operations within the scripts.

A. Test Commands

The test command (also known as, square brackets [ ] ) is a built-in command used to perform test operations on files, integers and strings. It takes an expression and returns an exit status of 0 if the conditional expression is true and a non-zero if the conditional expression is false.

Basic Syntax >

test condition

OR

[ condition ]

B. Conditional Test Operators in Bash

So far, you have understood how the test commands work in Bash scripts. Now, it’s time to learn how to build the test expressions using the test operators. The test operators are nothing but flags that you can easily pass to the test commands.

Actually, Bash offers a lot of conditional test operators that you can apply in different decision-making situations. Here, I’m going to mention some commonly used conditional test operators in Bash:

Test Operators Purpose
-eq Checks if two values are equal.
-ne Checks if two values are not equal.
-lt Checks if one value is less than another one.
-le Checks if one value is less than or equal to another one.
-gt Checks if one value is greater than another one.
-ge Checks if one value is greater than or equal to another one.
== or = Tests if two strings are equal.
!= Tests if two strings are not equal.
! Tests if the expression is false.
-n Checks if a string is non-empty.
-z Checks if a string is empty.
-e Checks if the file exists.
-f Checks if the regular file exists.
-d Checks if the directory exists.
-s Checks if a non-empty file exists.
-h Checks if an existent file is a symlink (symbolic link).
&& AND operator executes the results if all the conditions are true.
|| OR operator executes the results if at least one of the conditions is true.
-r Verifies if the file has read permission.
-w Verifies if the file has write permission.
-x Verifies if the file has execute permission.

How to Use Different Types of Conditional Statements in Bash

In Bash scripting, conditional statements assess single or multiple conditions and perform several actions according to the conditions. These conditionals can be of various types. In the following section, I’m going to share how Bash conditional statements, i.e. if, if-else, if-elif-else, nested if, case works differently for multiple decision-making purposes.

Type 01: “If” Conditional Statement in Bash

In Bash, if is the most commonly used conditional statement that allows you to control the flow of a script. The if statement is actually used to test a condition and make decisions based on specific criteria.

Basic Syntax >

if [ condition ]; then
#command to execute if the condition is true
fi

Here, if the condition becomes true after checking it with the if statement, a particular code is executed within the script but if the condition is false, the statement does nothing and there will be no execution.

Steps to Follow >

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

    Opening the file in Nano text editor in bash

  2. Now, write the following script inside the editor:
    Script (if.sh) >
    #!/bin/bash
    
    echo "Enter a number:"
    read number
    
    if [ $number -gt 20 ]; then
    echo "$number is greater than 20."
    fi
    EXPLANATION

    In #!/bin/bash, ‘#!’ is called Shebang’ or ‘Hashbang. The script prompts the user to enter a number and checks if the value stored in the number variable is greater than 20 using the comparison operator -gt. If the condition becomes true, the script displays a confirmation message using the echo command.

  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.sh
    EXPLANATION
    • chmod: Changes the permission of the files and directories.
    • u+x: Adds the executable permission for the user.
    • if.sh: The file which you want to make executable.
  5. Finally, run the script by the following command:
    ./if.sh

    Using if conditional statement to check if the entered number is greater than 20

    From the image, you can see that the number checking is done successfully using the if statement.

Type 02: “If-Else” Statement in Bash

Using the if statement, you can only perform a certain execution as long as a condition is satisfied. But what to do when you need to perform an operation when the condition is not satisfied? For this, you can use the if-else conditional statement to make your Bash scripts more flexible. It is a kind of statement that is used to check one condition and execute individual set of codes based on the conditions i.e. true or false.

Basic Syntax >

if [ condition ]; then
#command1
else
#command2
fi

Here, command1 will be executed if the condition becomes true. But if the result of the condition is false, then command2 will be executed.

You can follow the Steps of Type 01, to save & make the script executable.

Script (if_else.sh) >

#!/bin/bash

echo "What is your name?"
read person
right_person="X"

if [ "$person" == "$right_person" ]; then
    echo "Yes! You're the right person!"
else
    echo "Sorry, Better luck next time!"
fi
EXPLANATION

First, the above script uses the read command to read the user input. Then, it compares the name with the predefined name X and displays different messages depending on the match using the echo command.

Now, run the script by the following command:

./if_else.sh

Using if-else statements to check the right person in bash

From the image, you can see that using the ‘if-else’ statement can easily be used to verify the correct person with the correct name.

Type 03: “If-Elif (Else If)-Else” Statement in Bash

Sometimes, it becomes necessary to verify multiple conditions under a conditional construct and execute tasks accordingly. In this effort, else-if (elif) statement serves as the fundamental one. With this conditional statement, you can test multiple conditions and execute different commands accordingly.

Basic Syntax >

if [ condition1 ]; then
#command to execute if condition1 is true
elif [ condition2 ]; then
#command to execute if condition2 is true
…
else
#command  to execute if all conditions are false
fi

Here, when condition1 and condition2 are true, the if and elif statements execute the specific commands and this process continues. But when all the conditions become false, then the else statement is executed.

You can follow the Steps of Type 01, to save & make the script executable.

Script (else_if.sh) >

#!/bin/bash

echo "Enter a number:"
read number

if [ $number -gt 0 ]; then
    echo "Positive number"
elif [ $number -lt 0 ]; then
    echo "Negative number"
else
    echo "Neither positive number nor negative number"
fi
EXPLANATION

Here, the script first reads a number from the user, checks if the number is positive, negative or zero and then uses the echo command to display the appropriate output.

Now, run the script by the following command:

./else_if.sh

Using if-elif-else conditional statements to check positive or negative number in bash

The above image depicts the ‘if-elif-else’ conditional statement in case of verifying whether a number is positive, negative or neither (zero) of these.

Type 04: Nested If Statement in Bash

You can use nested-if statements when you need to create more complex decision-making logic based on different levels of conditional criteria. However, don’t use too many nested levels because excessive nesting can make your code more difficult and harder to understand.

Basic Syntax >

if [ condition1 ]; then
    #command to execute if condition1 is true
    if [ condition2 ]; then
        #command to execute if condition1 and condition2 both are true
    else
        #command to execute if condition1 is true but condition2 is false
    fi
else
    #command to execute if condition1 is false
fi

Here, when condition1 is true, the if statement proceeds to the nested-if statement. Inside the inner if statement, when condition2 is true, the if statement executes and when condition2 is false, the else block executes. The outer if statement also has an else block that executes commands when condition1 is false.

You can follow the Steps of Type 01, to save & make the script executable.

Script (nest.sh) >

#!/bin/bash

#Nested if statement
echo "Enter your exam score:"
read mark

if [ $mark -ge 0 ] && [ $mark -le 100 ]; then
    if [ $mark -ge 50 ]; then
        echo "You successfully passed the exam."
    else
        echo "Unfortunately, you failed the exam."
    fi
else
    echo "Invalid mark"
fi
EXPLANATION

The script first prompts the user to enter the exam score. Then, it checks the validity of the score using a ‘if’ statement. If the inserted score is valid, the script enters the nested-if statement and provides feedback like if the user passed or failed the exam based on the checking. Finally, the script prints the actual output using the echo command.

Now, run the script by the following command:

./nest.sh

Using nested if conditional statement to check a student's exam score

From the image, you can see that using the nested-if conditional statement, different levels of score decisions are met like pass, fail, and invalid mark.

Type 05: Case or Switch Statement in Bash

The case or switch statement is another powerful conditional tool that verifies multiple conditions and handles them based on a single variable’s value. This statement generally allows you to compare a variable with different patterns and executes specific commands that match with the particular pattern.

Basic Syntax >

case  <variable> in
   Pattern 1) <Task 1>;;
   Pattern 2) <Task 2>;;
   Pattern 3) <Task 3>;;
   …
esac

Here, when a match is found among all of the associated patterns, the case statement will execute the specific code block for that match and will be terminated after the last command execution. But if there is no match, the exit status of the case will be zero.

You can follow the Steps of Type 01, to save & make the script executable.

Script (case.sh) >

#!/bin/bash

echo "Enter a number (1-3):"
read segment

case $segment in
    1) echo "Opening time: 8PM";;
    2) echo "Break: 2PM-3PM";;
    3) echo "Closing time: 5PM";;
    *) echo "Invalid input"
esac
EXPLANATION

This script uses the read command to read the user input and displays the schedule for the specific segment according to the user input employing the echo command. Here, if the input is not 1, 2 or 3, then, the script echoes an invalid input message.

Now, run the script by the following command:

./case.sh

Using case statement to check different segments in a day

The above image indicates the ‘case’ statement for determining specific segments for different schedules.

Conclusion

To sum up, conditional statements are the powerful constructs in Bash scripting that enable you to control the flow and behavior of your scripts, make decisions and ensure dynamic response based on the specific conditions.

People Also Ask

Why the ‘fi’ Keyword is Used in Bash Conditional Statements?

The fi keyword is used to denote the end of an if statement in Bash.

Why the ‘elif’ Statement is Used in Bash Conditional Statements?

When the initial if condition is not satisfied, the elif statement is used to check as an alternative conditional in Bash.

Does Bash Have Any Built-in Ternary Operators for Conditional Expressions?

No, Bash doesn’t have any built-in ternary operators for conditional expressions.

Related Articles


<< Go Back to Bash Scripting Tutorial

4.8/5 - (6 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
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