Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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

like image 598
jackhab Avatar asked Mar 12 '13 15:03

jackhab


People also ask

Does spacing matter in bash?

It doesn't matter much whether how many space you indent, though most people seem to use 4 spaces or 8. Just make sure that your do's and done's line up and you'll be fine.

Is bash whitespace sensitive?

Bash indenting is very sensitive to characters. For example a space behind “do” in while/for loops will throw it of. When you have nested loops this is very ugly, and makes it hard to follow the code.

Does bash ignore whitespace?

Bash uses whitespace to determine where words begin and end. The first word is the command name and additional words become arguments to that command.

What does == mean in bash?

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison.


2 Answers

"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.

like image 190
chepner Avatar answered Sep 23 '22 08:09

chepner


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

like image 39
Gilles Quenot Avatar answered Sep 23 '22 08:09

Gilles Quenot