Bash Logical Operators

Bash logical operators are essential components of shell scripting that enable you to create conditional expressions and make decisions based on the evaluation of conditions. By combining these operators with various conditions, you can control the flow of your Bash scripts, allowing them to perform different actions based on specific criteria. In this article, I will discuss the role of logical operators and their functionality in bash script. So let’s move on!

Free Downloads

Basics of Logical/Boolean Operators in Bash

In Bash scripting, you can utilize logical operators to assess conditions and construct intricate expressions by merging two or more conditions. These operators enable you to determine whether a condition or a set of conditions holds true, granting you the ability to manage the script’s execution flow effectively. In the following section, I will give you an overall demonstration of the types of logical operators in bash script.

What are the Types of Logical Operators in Bash?

In Bash scripting, logical operators are fundamental for making decisions and controlling the flow of commands based on conditions. They evaluate conditions to be either true or false and make a decision based on the result of the condition. The three primary logical operators are AND, OR, and NOT operators. Let’s have a syntax of each operator below.

  • AND Operator: The AND operator in Bash denoted as “&&,” produces a true outcome solely when both assessed conditions are true. The syntax for the AND operator in Bash scripting is “&&”.
  • OR Operator: The OR operator evaluates to true if at least one of the conditions it connects evaluates to true. The syntax for the OR operator in Bash scripting is “||”.
  • NOT Operator: The NOT operator in Bash scripting reverses the outcome of a condition. It is denoted by the “!syntax and is used to negate the result of a given condition.

3 Cases of Using Logical Operators in Bash Scripting

In the following section of this article, I will show you the practical cases of bash logical operators to give a sense of their functionality.

Case 01: Combining Conditions With Logical Operators

In our first code, I will incorporate two logical AND operators and an echo command to display the output of the command.

The objective of this code is to check two conditions simultaneously using Bash scripting. It aims to determine whether a student’s grade is greater than or equal to 4 and whether the name matches the string “Bob.”

Steps to Follow >

  1. At first, launch an Ubuntu Terminal.
  2. Write the following command to open a file in Nano:
    nano conditional_operators.sh
    EXPLANATION
    • nano: Opens a file in the Nano text editor.
    • conditional_operators.sh: Name of the file.
  3. Copy the script mentioned below:
    #!/bin/bash
    grade=5
    name="Bob"
    
    [[ $grade -ge 4 && $name == "Bob" ]] && echo "Student name is $name and Grade is Greater than 4"
    
    EXPLANATION

    This Bash script begins by assigning the variables grade to 5 and name to Bob. It then uses a conditional statement within double square brackets ‘[[‘ to check two conditions simultaneously. The first condition, $grade -ge 4, evaluates whether the grade variable is greater than or equal to 4. The second condition, $name == “Bob“, checks if the name variable equals Bob.

    The && operator ensures that both conditions must be true for the subsequent command to execute. If both conditions are met, it echoes the message “Student name is Bob and Grade is Greater than 4” to the console.

  4. Press CTRL+O and ENTER to save the file; CTRL+X to exit the nano editor.
  5. Use the following command to make the file executable:
    chmod u+x conditional_operators.sh
    EXPLANATION
    • chmod: Changes the permissions of files and directories.
    • u+x: Here, u refers to the “user” or the owner of the file and +x specifies the permission being added, in this case, the “execute” permission. When u+x is added to the file permissions, it grants the user (owner) permission to execute (run) the file.
    • conditional_operators.sh: Script file name.
  6. Run the script by the following command:
    ./conditional_operators.sh

    Combining Conditions with Logical OperatorsUpon execution, the code displays “Student name is Bob and Grade is Greater than 4”.

Case 02: Logical Operators in If-Else Statements

In this case, I will employ if-else statement with the AND logical operator. The objective of this Bash script is to check whether a person named John, whose age and student status are provided as commandline arguments, meets specific criteria. It verifies if John is older than 18 years and is identified as a student, and accordingly, it outputs a message confirming or denying these conditions.

You can follow the steps of Case 01, to save & make the script executable.

Script (condition_Operators.sh) >

#!/bin/bash

# Check if the number of arguments is less than 3
if [ $# -lt 3 ]; then
    echo "Usage: $0 <age> <name> <is_student>"
    exit 1
fi

age=$1
name=$2
is_student=$3

if [[ $age -gt 18 && $name == "John" && $is_student == true ]]; then
    echo "John is older than 18 and is a student."
else
    echo "John does not meet all the specified conditions."
fi
EXPLANATION

This Bash script starts by checking if the number of commandline arguments provided is less than 3 using the $# variable, which holds the number of arguments. If there are fewer than 3 arguments, it displays a usage message and exits. Then, it assigns the variables age, name, and is_student with the positional parameters $1, $2 and $3 respectively.

Next, it uses an if statement with double square brackets [[ … ]] to check multiple conditions. It verifies whether the age stored in the age variable is greater than 18, whether the name variable contains the string “John,” and whether the is_student variable is set to true. If all these conditions are met, it prints the message “John is older than 18 and is a student.” Otherwise, it displays “John does not meet all the specified conditions.”

Use the following command to run the script:

./condition_Operators.sh 21 John true

Logical Operators in if-else StatementsUpon execution, the bash script returns “John is older than 18 and is a student” to the command line.

Case 03: Combining Multiple Boolean Operators in a Bash Script

In this segment, I will now incorporate multiple booleans aka logical operators. The objective of this Bash script is to determine whether Alice is eligible based on certain conditions related to her age, name, and student status, and to provide an appropriate message indicating whether she meets these conditions or not.

You can follow the steps of Case 01, to save & make the script executable.

Script (multiple_boolean.sh) >

#!/bin/bash
age=25
name="Alice"
is_student=true

if [[ $age -ge 18 && $name != "Bob" || ($is_student == true && $age -le 30) ]]; then
    echo "Alice is eligible: older than 18, not named Bob, and either a student or under 30 years old."
else
    echo "Alice does not meet the specified conditions."
fi
EXPLANATION

This Bash script initializes variables for age, name, and student status. It then uses an if statement with logical operators to check if Alice’s age is greater than or equal to 18, her name is not Bob, and she is either a student or under 30 years old. If all these conditions are met, it prints that Alice is eligible; otherwise, it states that she does not meet the specified conditions.

Use the following command to run the script:

./multiple_boolean.sh

Combining Multiple Boolean Operators in a Bash ScriptAs the name and age variable contain Alice and 25 respectively, the code returns “Alice is eligible: older than 18, not named Bob, and either a student or under 30 years old.”

5 Practical Examples of Using Logical Operators in Bash Scripting

Previously I showed three different scenarios to incorporate the logical operators in bash script. However, the following section will give five different examples by using the logical operator.

Example 01: Check if a Number is Within a Specific Range

You can create complex expressions by combining conditions using logical operators. For instance, the objective of this given Bash script is to assess whether a given numerical value, provided as a command-line argument, falls within the specified range of 10 to 20.

You can follow the steps of Case 01, to save & make the script executable.

Script (number_range.sh) >

#!/bin/bash

value=$1
 
if [[ $value -gt 10 && $value -lt 20 ]]; then
  echo "The value is within the range of 10 to 20."
else
  echo "The value is not within the range of 10 to 20."
fi
EXPLANATION

This Bash script takes a single commandline argument value and checks if it falls within the range of 10 to 20 using an if statement with the && logical operator. If the value is greater than 10 AND less than 20, it prints “The value is within the range of 10 to 20.” Otherwise, it prints “The value is not within the range of 10 to 20.”

To run the script, Use the following command:

./number_range.sh 34
./number_range.sh 15

Check if a Number is within a Specific RangeUpon giving 34 for as a command line argument to number_range.sh bash file, the code returns  “The value is not within the range of 10 to 20.” On the other hand, number_range.sh with given 15 as argument displays “The value is within the range of 10 to 20.”

Example 02: Check if a User is Either “root” or “admin” Using Boolean Operators

Next, I will use the OR operator in my second code. The objective of this code is to determine whether a user, represented by the variable username, is either root or admin and ascertain if the user has administrative privileges on the system.

You can follow the steps of Case 01, to save & make the script executable.

Script (check_root.sh) >

#!/bin/bash

# Define the username you want to check
username="$1"

# Check if the user is either the root user or has sudo privileges
if [ "$UID" -eq 0 ] || sudo -lU "$username" | grep -q "(ALL : ALL)"; then
  echo "$username has sudo privileges, hence is either root or admin user"
else
  echo "The username '$username' is neither root nor has sudo privileges."
fi
EXPLANATION

This Bash script begins by capturing a username provided as an argument when running the script. It proceeds to check two conditions using the if statement. First, it examines whether the effective user ID (UID) of the user executing the script is equal to 0, which signifies the root user.

Second, it employs the sudo command to evaluate whether the specified username has sudo privileges. The grep -q part in this condition silences any output and checks if the pattern (ALL : ALL) exists in the sudo configuration, indicating sudo privileges. If either condition is true, the script prints a message declaring that the user possesses sudo privileges and is thus either the root user or an admin user. Conversely, if neither condition is met, it communicates that the username is neither the root user nor has sudo privileges.

Now run the script by using the following command:

./check_root.sh John
./check_root.sh miran

 Check if a User is Either “root” or “admin” Using Boolean OperatorsIn the image depicted above, John is a newly created user who does not have the sudo privilege. By incorporating John as the positional argument, the command line says John does not have any sudo privilege. On the contrary, miran is the current user and has the sudo privilege. Therefore the script validates miran’s authority upon execution of the script accordingly.

Example 03: Invert a Condition Using the “NOT” Operator

Moving forward to our next example, I have shown the image attached below where there is a text_file.txt in the current directory.Invert a Condition Using the NOT Operator-1 Now I will provide a bash code with the aid of the logical operator. The objective of this code is to check whether a file named test_file.txt exists in the current directory or not. If the file exists, it displays a message confirming its existence; otherwise, it outputs a message indicating that the file does not exist.

You can follow the steps of Case 01, to save & make the script executable.

Script (file_test.sh) >

#!/bin/bash

# Define a new filename
file_to_check=$1

# Check if the file exists
if [[ ! -e "$file_to_check" ]]; then
  echo "The file '$file_to_check' does not exist."
else
  echo "The file '$file_to_check' exists."
fi
EXPLANATION

This Bash script begins by defining a variable named file_to_check and assigns it the value test_file.txt. It then uses an if statement to check if the file specified by file_to_check exists in the current directory, utilizing the -e test operator within double square brackets. If the file does not exist, it outputs a message indicating that the file is not present. Conversely, if the file exists, it outputs a message confirming its existence.

Use the following command to run the script:

./file_test.sh test_file.txt

Invert a Condition Using the NOT Operator-2As the test_file.txt already exists in the current directory, it is obvious the code will return “The file ‘test_file.txt’ exists’ to the command line.

Example 04: Using of “NOT” and “AND” Logical Operators in a Single Line

As I have stated in Case 03, you can use multiple bash logical operators to get the job done. Here I have developed a code below with the help of both NOT and AND operators.

The objective of this code is to create a Bash script that serves as a Voting Eligibility Checker. Follow the script given below.

You can follow the steps of Case 01, to save & make the script executable.

Script (and_not.sh) >

#!/bin/bash

# Prompt the user to enter their age and whether they have a voting disqualification
echo "Welcome to the Voting Eligibility Checker!"
read -p "Please enter your age: " age
read -p "Do you have any voting disqualifications? (yes or no): " disqualifications

# Check if the user is old enough and not disqualified
if [ $age -ge 18 ] && [ "$disqualifications" != "yes" ]; then
    echo "Congratulations! You are eligible to vote."
else
    echo "Sorry, you are not eligible to vote at the moment."
fi
EXPLANATION

The given bash code starts by prompting the user to enter their age and whether they have any voting disqualifications. It uses the read command to capture these inputs. Then, it uses an if statement to check if the user’s age is greater than or equal to 18 and if their response to disqualifications is not yes. If both conditions are met, it prints “Congratulations! You are eligible to vote.” Otherwise, it prints “Sorry, you are not eligible to vote at the moment.

Use the following command to run the script:

./and_not.sh

Using of OR and NOT Operator in a Single LineAs you can see from the image given above, I inserted 25 as my age and gave a “no” response regarding my voting disqualifications. Thus the code gives the output Congratulations! You are eligible to vote, based on the conditions set.

Example 05: Using of “OR” and “NOT” Operator in a Single Line

Like the script described in the example just above, you can also incorporate OR and NOT logical operators in your code. Just look at the code described below. Here, I have developed a simple code to verify the username and password and serve a greeting if the user provides input correctly.

You can follow the steps of Case 01, to save & make the script executable.

Script (or_not.sh) >

#!/bin/bash

echo "Give your correct username and password to get a greeting"

# Set the correct username and password
correct_username="miran"
correct_password="1234"

# Prompt the user to enter their credentials
read -p "Enter your username: " username
read -s -p "Enter your password: " password

# Check if the entered credentials are correct
if [ "$username" != "$correct_username" ] || [ "$password" != "$correct_password" ]; then
    echo -e "\nLogin failed. Invalid username or password."
else
    echo -e "\nLogin successful! Welcome, $username."
fi
EXPLANATION

The code begins by printing a message asking the user to provide their correct username and password for a greeting. The correct username and password are defined as “miran” and 1234 in the script. The script uses the read command to prompt the user to enter their username and password. The -s flag with read is used for the password input to keep it hidden as the user types.

It then uses an if statement to check if the entered username and password match the correct ones. If either the username or password is incorrect, it prints “Login failed. Invalid username or password.” Otherwise, if both are correct, it prints “Login successful! Welcome, [username].”

Use the following command to run the script:

./or_not.sh

Using of NOT and AND Logical Operators in a Single LineAs the user correctly provides the username and password, the code returns “Login successful! Welcome, miran” on the command line.

Conclusion

In conclusion, Logical operators in bash scripting can play a vital role in assigning multiple conditions and making decisions based on them. In this article, I have demonstrated some different examples of logical operators in bash to convey its functionality. If you have any questions or queries related to this, feel free to comment below. I will get back to you soon. Till then, Happy Coding!

People Also Ask

What are logical operators in Bash?

Logical operators in Bash include && (AND), || (OR), and ! (NOT). They are used to perform logical comparisons and control the flow of commands based on conditions.

What is the += operator in Bash?

In Bash, the += operator is a compound assignment operator that allows you to add (concatenate) a string or value to the end of an existing variable’s value. It’s commonly used for building or modifying strings dynamically in scripts.

What is binary operator in Bash?

A binary operator in Bash is an operator that works on two operands or values. It requires two values to perform an operation, such as addition, subtraction, comparison, or logical operations. Examples of binary operators in Bash include + for addition, for subtraction, == for equality comparison, and && for logical AND operations.

What is the use of && in Bash?

In Bash, && is a logical operator used to execute the command on its right only if the command on its left succeeds (returns a zero exit status).

Related Articles


<< Go Back to Bash Operator | Bash Scripting Tutorial

4.9/5 - (15 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment