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
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.
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.
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.
== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison.
"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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With