Usage of “OR” Operator in Bash Scripting [2 Cases]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Bash includes a range of logical operators that help to set multiple conditions within a bash script. Among these, the logical OR operator, denoted by “||” in Bash, executes Boolean OR operations. In this article, I will demonstrate an overall picture of the OR operator in bash scripts, including its syntax, different user cases, and examples. So let’s begin.

Key Takeaways

  • Getting familiar with the OR operator and its syntax.
  • Understanding the implication of if statement or while loop along with the OR operator in bash.

Free Downloads

“OR” Operator in Bash Scripting

In bash scripting, a developer can use OR operator to develop his code aiming to menu selection, file existence, error handling, verify the user data, etc. To begin with all of those effective applications, let’s understand the syntax and the mechanism of the bash OR operator first.

Syntax of “OR” Operator

Within the logical operators of the bash script, you’ll find the logical OR operator, which carries out a boolean OR operation. One single Bash boolean OR operator accepts two operands and yields a true outcome if either of them is true, otherwise, it results in a false. The syntax of the OR operator is as such.

operand_1 || operand_2

Here, operand_1 and operand_2 represent logical expressions or boolean conditions that produce either a true or false result. In Bash, the || operator performs the boolean OR operation.

Truth Table of Bash “OR” Operator

Following the syntax of the OR operator provided above, the OR operator in Bash assesses two logical expressions and yields a true outcome if either of them is true, otherwise, it produces a false result.  Below is a truth table for the Bash logical OR operator, serving as a helpful reference to grasp its behavior:

Operand_1 Operand_2 Operand_1 || Operand_2
True True True
True False True
False True True
False False False

2 Practical Cases of Using “OR” Operator in Bash Scripting

Down below, I am going to discuss several practical cases with examples to demonstrate you the overall idea of the OR operator in bash. Check this out and don’t forget to run the code in your command line.

Case 01: Using Bash “OR” Operator in IF Condition

The Bash OR operator in an if condition allows for the execution of a code block when at least one of the provided conditions is true. This flexibility enables various scenarios where different conditions can trigger specific actions based on the outcome. Let’s have three examples to grasp the idea of it.

Example 01: Check If a Number is Between a Specific Range

The objective of the provided Bash script is to allow a user to input a number and determine whether that number falls within the range of 10 to 20. It uses conditional statements to check if the input number is either less than 10 or greater than 20, and based on the evaluation, it provides user feedback.

Steps to Follow >

  1. At first, launch an Ubuntu Terminal.
  2. Write the following command to open a file in Nano:
    nano number_check.sh
    EXPLANATION
    • nano: Opens a file in the Nano text editor.
    • number_check.sh : Name of the file.
  3. Copy the script mentioned below:
    #!/bin/bash
    
    read -p "Enter a number: " number
    
    if [ $number -lt 10 ] || [ $number -gt 20 ]; then
        echo "The number is not between 10 and 20."
    else
        echo "The number is between 10 and 20."
    fi
    
    EXPLANATION

    This Bash script begins with the shebang #!/bin/bash, indicating that it should be executed using the Bash shell. It proceeds to ask the user to input a number using the read command, and the entered number is stored in the number variable. The script then uses an if statement to evaluate whether the value of number is less than 10 or greater than 20. If either condition is met, as denoted by the logical OR operator ||, the script displays the message “The number is not between 10 and 20.” Conversely, if neither condition is true, it prints “The number is between 10 and 20.”

  4. Press CTRL+O and ENTER to save the file; CTRL+X to exit.
  5. Use the following command to make the file executable:
    chmod u+x number_check.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. u+x grants the user (owner) permission to execute (run) the file.
    • number_check.sh : File name.
  6. Run the script by the following command:
    ./number_check.sh

    Check If a Number is between a Specific RangeWhile 35 is passed as the user input, the bash code evaluates it and returns The number is not between 10 and 20 to the command line. Subsequently, when the number 12 is provided, the code declares the value as a number that lies between 10 and 20.

Example 02: Check If a Number is Even or Divisible by 5

In a different scenario, I will now examine whether the provided number is divisible by 2 (making it even) or divisible by 5. To accomplish this, I’ve developed a Bash script given below.

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

Script (number_check2.sh) >

#!/bin/bash

read -p "Enter a number: " number

if [ $((number % 2)) -eq 0 ] || [ $((number % 5)) -eq 0 ]; then
    if [ $((number % 2)) -eq 0 ]; then
        echo "The number is even."
    fi

    if [ $((number % 5)) -eq 0 ]; then
        echo "The number is divisible by 5."
    fi
else
    echo "The number is neither even nor divisible by 5."
fi
EXPLANATION

In this Bash script, the user is prompted to input a number. The script then uses a conditional statement to check if the number is either even (divisible by 2) or divisible by 5. If either condition is true, it provides specific messages: “The number is even” if it’s divisible by 2 and “The number is divisible by 5” if it’s divisible by 5. If neither condition is met, it prints “The number is neither even nor divisible by 5.” The script uses the logical OR operator (||) in the initial if statement to check for either of the two conditions and then uses nested if statements to handle each condition individually.

To run the code, execute the following command to the command line.

./number_check2.sh

Check If a Number is Even or Divisible by 5Upon giving 23 and 10 as user input, the command line returns 23 as neither even nor divisible by 5, 10 as an even number, and divisible by 5.

Example 03: Check Condition Using “-o” Operator

Other than using the OR (||) operator, you can accomplish the same using the -o Operator. Follow the code given below to understand it’s functionality.

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

Script (o_operator.sh) >

#!/bin/bash

read -p "Enter a number: " number

if [ $((number % 2)) -eq 0 -o $((number % 5)) -eq 0 ]; then
    echo "The number is either even or divisible by 5."
else
    echo "The number is neither even nor divisible by 5."
fi
EXPLANATION

In this Bash script, the user is prompted to input a number. The script then uses a conditional statement to check whether the number is either even (divisible by 2) or divisible by 5. If either condition is true, it prints “The number is either even or divisible by 5” using the echo command. Otherwise, it prints “The number is neither even nor divisible by 5.” The -o operator represents the logical OR operation in the conditional statement.

Use the following command to run the code in the command line.

./o_operator.sh

Check Condition Using “-o” OperatorUpon executing the bash file, as you can see from the image given above, the code returns 5 as a number either to be even or divisible by 5 and 9 as a number neither even nor divisible by 5.

Case 02: Bash “OR” Operator in “While Loop” Expression

In Bash, you can also use the OR operator (||) in the expression of a while loop to create a loop that continues running as long as either of the specified conditions is true. Here’s a sample code provided below. The objective of this Bash script is to present a simple menu to the user, allowing them to choose between starting a new game or quitting. The script uses a while loop with the OR operator to continue running until a valid choice of either 1 or 2 is made by the user.

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

Script (while_or.sh) >

#!/bin/bash

choice=""

while [ "$choice" != "1" ] || [ "$choice" != "2" ]; do
    echo "Choose an option:"
    echo "1. Start a new game"
    echo "2. Quit"

    read -p "Enter your choice (1 or 2): " choice

    if [ "$choice" == "1" ]; then
        echo "Starting a new game..."
        # Add game start logic here
    elif [ "$choice" == "2" ]; then
        echo "Goodbye!"
        break
    else
        echo "Invalid choice. Please enter 1 or 2."
    fi
done
EXPLANATION

In this Bash script, a while loop is established with the OR operator (||) in its condition, ensuring the loop continues as long as the user’s input for choice is not both 1 and 2 simultaneously. The user is prompted to select between starting a new game (option 1) or quitting (option 2). Based on the user’s input, the script executes the respective logic, either starting a new game (indicated by a comment) or exiting with a Goodbye! message. If the user enters an invalid choice, they will try again until they select 1 or 2.

Run the script using the following command:

./while_or.sh

Bash OR Operator in While Loop ExpressionAs you can see from the image given above, the code starts a new game when the user presses 1 and ends the execution once the user gives 2 as the user input.

Assignment on Bash “OR” Operator

Here for your perusal, I have given to an assignment to asses your overall proficiency from today’s learning. Don’t forget to share with others in the comment section.

  1. Write a Bash script that prompts the user to input their age and checks whether the user is elder or younger. If the age is less than 18 then the user will be regarded as younger, older otherwise. Provide appropriate messages based on the conditions.
  2. Write a bash code to print a set of numbers using or operator in a loop.

Conclusion

In conclusion, this article delves into the effective utilization of the OR operator in Bash scripting. It thoroughly explains the syntax of the OR operator, emphasizing its role in performing logical OR operations. Then it returns a true result when either of the two operands is true. The article also provides valuable insights into the OR operator’s practical applications, with a focus on its use in IF conditions and within while loop expressions. However, if you have any questions or queries related to this article, feel free to comment below. Thank you.

People Also Ask

What does @$ mean in Bash?

In Bash, $@ represents all the arguments passed to a script or function as individual parameters. Each argument is treated separately and can be accessed using $1, $2, and so on. It passes all the arguments to another function or command within a script.

What is the difference between && and || in bash script?
In Bash scripts, && and || are used as logical operators. && represents the logical AND operator, and it returns true only if both operands are true. On the other hand, || is logical OR operator, and it returns true if either of the operands is true. So, the key distinction is that && requires both conditions to be true, while || only needs one condition to be true.
What does == mean in Bash?
In Bash, == dedicates for string comparison. It is an operator that checks whether two strings are equal. If the strings match, it returns true; otherwise, it returns false.
What does $1 /* mean in Bash?
In Bash, $1 refers to the first argument passed to a script or function. On the other hand, “/” is a wildcard that represents all files and directories in the root directory. So, “$1 /” means to use the first argument as a directory path and append “/*” to it. Therefore it effectively represents all files and directories within that specified directory.

Related Articles


<< Go Back to Bash Logical Operators | Bash Operator | Bash Scripting Tutorial

5/5 - (6 votes)
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