Bash Scripting: Conditionals

A conditional in Bash scripting is made up of two things: a conditional statement and one or more conditional operators.

Bash scripts give us two options for writing conditional statements. We can either use an if statement or a case statement. In some situations, a nested if statement can also be helpful. These conditional statements only work by using operators. An operator could tell the statement to check if two numbers are equal, or if one is greater than other, etc.

The combination of conditional statements and operators is how we write Bash scripts that can proceed with a specific set of instructions depending on whether or not a condition matches our specifications. In this tutorial, you will learn how to use conditionals in Bash scripting on a Linux system.

In this tutorial you will learn:

  • How to use if and case conditional statements
  • How to use conditional operators
Simple example of using conditional statements and operators in a Bash script on Linux
Simple example of using conditional statements and operators in a Bash script on Linux
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software Bash shell (installed by default)
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Bash Scripting: Conditionals examples



Twitter icon Follow LinuxConfig.org on Twitter for the latest tips and tricks about Linux!


First, let’s look at the operators that we can use with our conditional statements in a Bash script. Then, we will put these operators to use in the examples below.

Conditional Operators

We can either compare numbers or strings in our conditional statements, so we have separated the operators into arithmetic and string comparisons in the tables below.

Arithmetic Comparisons

-lt <
-gt >
-le <=
-ge >=
-eq ==
-ne !=

String Comparisons

= equal
!= not equal
< less than
> greater than
-n s1 string s1 is not empty
-z s1 string s1 is empty

Conditional Statement Examples

  1. Let’s start with what is probably the most basic conditional script possible. The script below uses an if statement and will just check to make sure that two numbers you enter are equal to each other.
    #!/bin/bash
    
    echo "enter the first number"
    read num1
    
    echo "enter the second number"
    read num2
    
    if [ $num1 -eq $num2 ]; then
            echo "the numbers match"
    else
            echo "the number do NOT match"
    fi

    Here is the result when we execute the script and enter two matching numbers:

    $ ./test.sh 
    enter the first number
    3
    enter the second number
    3
    the numbers match
    




    Since our if statement used the -eq operator to determine if the two numbers are equal to each other, and they indeed are, the first clause was executed, thus we got “the numbers match” as output.

  2. Next, let’s try a simple conditional script with a case statement. Let’s look at a simple example which has statements tied to multiple patterns. This script will let us know whether today is a weekday or weekend.
    #!/bin/bash
    
    day=$(date +"%a")
    
    case $day in 
    
      Mon | Tue | Wed | Thu | Fri)
        echo "today is a weekday"
        ;;
    
      Sat | Sun) 
        echo "today is the weekend"
        ;;
    
      *)
        echo "date not recognized"
        ;; 
    esac

    And here is what happens when we execute the script:

    $ ./test.sh 
    today is a weekday
    

    In this case we do not need to use any conditional operators. However, the case statement is still comparing strings in order to determine which clause will be matched.

    What is happening in the script? The date +"%a" command is getting information about what day of the week it is. Then our case statement will check whether the result is Mon, Tue, Wed, Thu, or Fri. If it is, then it matches pattern number 1 and will echo “today is a weekday.” If that does not match, it checks to see if the date is Sat or Sun. If it is, the script echoes “today is the weekend.” Lastly, in case there is a problem with the system and the date command returns some other kind of information, the wildcard will be matched and we will get a “date not recognized” result.

  3. The third type of conditional statement we could create is a nested if. This works similarly to a regular if statement, except it has additional if statements nested into the parent one. In order for subsequent if statements to be triggered at all, the one preceding it must be realized first.
    #!/bin/bash
    
    # Determine the day of week and store it inside the $day variable
    day=$(date +"%u")
    # Determine if it is morning or night and store it in the $time variable
    time=$(date +"%p")
    
    # Check if the day of the week is between 1-5 (Mon-Fri)
    if [ $day -le 5 ]; then
            # if it is a weekday, echo the text below
            echo "today is a weekday"
            # now determine if it is morning or night time
            if [ $time == "AM" ]; then
                    echo "it is morning"
            else
                    echo "it is night"
            fi
    else
            # if the first condition was not met, execute the following command
            echo "today is the weekend!"
    fi

    We used a nested if statement and two conditional operators in this script. The first operator is -le, which checks if the integer stored in the $day variable is less than or equal to 5. The second operator is ==, which determines whether or not the string stored in the $time variable is equal to AM.

    Here is the output when we execute the script:

    $ date
    Fri 25 Feb 2022 09:55:14 PM EST
    
    $ ./test.sh 
    today is a weekday
    it is night
    
    




    The point of a nested if is that the second if statement is only used if the first if statement is true. In this case, our script only checks the time of day if it first determined that the day of the week is Mon-Fri. We have left comments in the script to make this easier to digest.

Closing Thoughts

In this tutorial, you saw how to use conditional statements and operators in a Bash script on Linux. Conditionals are an essential part of many Bash scripts, and give us the opportunity to adapt our scripts to a variety of situations, as certain parts can be configured to only execute when particular conditions are met.



Comments and Discussions
Linux Forum