Bash If statement with AND Operator

You can use AND logical operator to join two boolean expressions in the condition of an If statement in Bash scripting.

The syntax to join two simple conditions (boolean expressions) with AND operator in If statement’s condition is

if [ condition_1 ] && [ condition_2 ];
then
    statement(s)
fi

Reference Bash If Statement.

Example

In the following script, we check if given number is greater than 10 and even number. Here we have two conditions, and we join these two conditions using AND logical operator.

example.sh

#! /bin/bash
 
num=14

if [ $num -gt 10 ] && [ $((num%2)) -eq 0 ];
then
    echo "Number is greater than 10 and even."
fi

Output

sh-3.2# ./example.sh 
Number is greater than 10 and even.
ADVERTISEMENT

Conclusion

In this Bash Tutorial, we learned how to use AND logical operator in If statement, with the help of syntax and examples.