Skip to content

Logical Operations

General format

if [ arg1 operator arg2 ] ; then list

or 

if [ arg1 operator arg2 ] ; then list ; else list ; fi

Boolean Logic with [ ]

[ is the test command and uses –a and –o as the logical AND and OR operators respectively, between expressions.  

Like so: 

[ expr1 –a expr2 ]

[ expr1 –o expr2 ]

Can be replaced by: 

[ expr1 ] && [ expr2 ]

[ expr1 ] || [ expr2 ]

Boolean Logic with [[ ]]

The newer (bash-specific) [[ ]] syntax for logical operations allow the use of && and || between expressions to be tested. 

E.g. 

[[ expr1 && expr2 ]]

[[ expr1 || expr2 ]]

It also allows the use of regular expression string matching using the =~ operator,

E.g.

[[ $string =~ b[aeiou]t ]]