Reputation: 17698
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
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
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
The spaces are mandatory in a test expression
Upvotes: 4