Bash AND Logical Operator

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

Bash boolean AND operator takes two operands and returns true if both the operands are true, else it returns false.

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

Syntax of AND Operator

Following is the syntax of AND 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. It is read as double ampersand.

AND Truth Table

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

Operand_1Operand_2Operand_1 && Operand_2
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

Bash AND Operator in IF condition

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

We shall check if the number is even and also divisible by 10.

Bash Script File

</>
Copy
#!/bin/bash

num=50

if [ $((num % 2)) == 0 ] && [ $((num % 10)) == 0 ];
then
    echo "$num is even and also divisible 10."
fi

Output

50 is even and also divisible 10.

Bash AND Operator in While Loop Expression

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

Bash Script File

</>
Copy
#!/bin/bash
 
a=0
b=0
a_max=10
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

0
1
2
3
4
5

Conclusion

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