jackhab
jackhab

Reputation: 17698

Why does adding spaces around bash comparison operator change the result?

Could someone explain why spaces around == change the comparison result? The following:

if [[ 1 == 2 ]] ; then echo ok ; fi

prints nothing, while

if [[ 1==2 ]] ; then echo ok ; fi

prints ok

Upvotes: 8

Views: 434

Answers (2)

chepner
chepner

Reputation: 531315

"1==2" is a single 4-character string, not an expression involving the == operator. Non-empty strings always evaluate to true in the context of the conditional expression [[ ... ]]. Whitespace is mandatory around the == operator.

Like everything else in bash, the contents of [[ ... ]] are simply a white-space-separated list of arguments. The bash grammar doesn't know how to parse conditional expressions, but it does know how to interpret a list of 3 arguments like 1, ==, and 2 in the context of the [[ ... ]] compound command.

Upvotes: 15

Gilles Quénot
Gilles Quénot

Reputation: 185219

Because it's just a string, consider testing :

[[ foobar ]]

it will be true.

This is useful to test if a variable is set or not like in this example :

x='foobar'
[[ $x ]] # true

and now

x=''
[[ $x ]] # false

Finally

The spaces are mandatory in a test expression

Upvotes: 4

Related Questions