Last Updated: February 25, 2016
·
410
· gkb

Careful about the conditional operators in bash

You would think that [[ can be used wherever [ is used in bash. After all, it seems to be a better version of [. But you would save yourself some frustrating moments if you recognize the differences between them. Here's one difference worth noting.

Note that -a is the operator for 'and' in [.

[ ( 'hello' == 'hello' ) -a  ( 'world' == 'world' ) ] # WORKS

But you cannot construct compound conditions using -a in [[.

[[ ( 'hello' == 'hello' ) -a  ( 'world' == 'world' ) ]] # DOES NOT WORK

With [[, use the && operator instead.

[[ ( 'hello' == 'hello' ) &&  ( 'world' == 'world' ) ]] # WORKS