Logical AND (-a) and OR (-o)

You can sometimes avoid the need for nested if statements by using the logical AND (-a) and OR (-o) operators.  For example:

 


Logical AND (-a)

In the case of the logical AND (-a), both sides of the expression must be true in order for the result to be true.

Depending on the value of both sides of the expression, the table below illustrates what will be the logical result.


Logical OR (-o)

In the case of the logical OR (-o), one or both sides of the expression must be true in order for the result to be true.

Depending on the value of both sides of the expression, the table below illustrates what will be the logical result.

OR Example:

if [ -e file1 -o -e file2 ]
then
echo At least one file is there
fi


Order Precedence

The AND (-a) takes precedence over the OR (-o) in compound expressions.

Back-slashed parenthesis can be used to override the default precedence.


Example without back-slashed parenthesis: [ -e file1 -o -e file2 -a -e file3 ]    

 


Example with back-slashed parenthesis: [ \(-e file1 -o -e file2 \) -a -e file3 ]    


Logical NOT (!)

The logical NOT (!) can be used to negate or reverse the result of a logical expression.  It has the highest precedence of all operators.

For example: