BASH Programming

How to Do a Logical OR Operation for Integer Comparison in Shell Scripting

In shell scripting, we often need to compare integers and perform logical operations based on the comparison result and one common logical operation is the logical OR operation, which returns true if at least one of the operands is true. This article will explain performing a logical OR operation in shell scripting for integer comparison.

Comparing integer in Shell Scripting using Logical OR Operation

The logical OR operator in shell scripting is denoted by the double vertical bar or known as double pipe ||, the syntax of the OR operator is as follows:

if [ condition1 ] || [ condition2 ]
then
    # instruction to be executed if any of the condition1 or condition2 is true
fi

Here, condition1 and condition2 are expressions that evaluate to either true or false and the || operator returns true if any of the conditions is true, and false otherwise.

To perform a logical OR operation for integer comparison in shell scripting, we need to use comparison operators to compare the integers and the || operator to perform the OR operation, here’s an example:

#!/bin/bash
a=10
b=20
if [ $a -eq 10 ] || [ $b -eq 20 ]
then
    echo "Either a is equal to 10 or b is equal to 20"
fi

Here we compare the value of variable a with 10 using the -eq operator and the value of variable b with 20 using the same operator. We use the || operator to perform the logical OR operation and if either condition is true, the message “Either a is equal to 10 or b is equal to 20” is printed to the console.

To further illustrate comparing of integers using the OR operator there is another example given that checks if the given number is even or divisible by 5 so here is this shell script:

#!/bin/bash
 
n=20
 
if [ $((n % 2)) == 0 ] || [ $((n % 5)) == 0 ];
then
    echo "$n is even or divisible by 5."
fi

The script first sets “n” to 20 and then uses the modulo operator to check if “n” is evenly divisible by 2 or 5 and if either of these conditions are true, it prints the message “20 is even or divisible by 5.” The double brackets “[[]]” are used to group the logical conditions and the double parentheses “[()]” are used to evaluate arithmetic expressions. The script demonstrates the use of logical operators and conditional statements in Bash scripting:

Conclusion

The above guidelines explain the procedure to carry out a logical OR operation for integer comparison in shell scripting. The || operator can be used to perform the OR operation, and comparison operators such as -eq can be used to compare integers. By using such ways, we can write shell scripts that perform complex logical operations and automate many tasks efficiently.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.