Bash OR Logical Operator

Under Logical operators, Bash provides logical OR operator that performs boolean OR operation.

Bash boolean OR operator takes two operands and returns true if any of the operands is true, else it returns false.

OR logical operator combines two or more simple or compound conditions and forms a compound condition.

Syntax of OR Operator

Following is the syntax of OR logical operator in Bash scripting.

</>
Copy
operand_1 || operand_2

where operand_1 and operand_2 are logical expressions or boolean conditions that return either true or false. || is the operator used for AND boolean operation.

AND Truth Table

Following truth table gives information about the returned value by OR logical operator for different valid operand values.

Operand_1Operand_2Operand_1 && Operand_2
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

Bash OR Operator in IF condition

In the following example, we shall use Bash OR logical operator, to form a compound boolean expression for Bash IF.

We shall check if the number is even or if it also divisible by 5.

Bash Script File

</>
Copy
#!/bin/bash

num=50

if [ $((num % 2)) == 0 ] || [ $((num % 5)) == 0 ];
then
    echo "$num is even or divisible by 5."
fi

Output

50 is even or divisible by 5.

Bash OR Operator in While Loop Expression

In this example, we shall use Bash OR boolean logical operator in while expression.

Bash Script File

</>
Copy
#!/bin/bash
 
a=1
b=1
a_max=7
b_max=5
 
# and opertor used to form a compund expression
while [[ $a -lt $a_max+1 || $b -lt $b_max+1 ]]; do
   echo "$a"
   let a++
   let b++
done

Output

1
2
3
4
5
6
7

Conclusion

In this Bash Tutorial, we learned the syntax of Bash OR logical operator and how to use it in preparing compound expression for conditional statements or looping statements.