Why does bash have the following behavior?
echo $((true == false))
1
I would have thought that this wou
OK, so, it seems there is a lot of confusion about what $((...))
really does.
It does an arithmetic evaluation of its operands, barewords are variables, not commands or string literals (ie, true
is really $true
), and anything which is not a number is 0. The ==
operator compares two numbers, and returns 1 if they are equal.
Which is why $((true == false))
is 1: there is no true
or false
environment variables in the environment, which means both $true
and $false
evaluate to the empty string, therefore 0 in arithmetic context!
To be complete, you can also use command substitution in arithmetic context... For instance:
$ echo $((`echo 2`))
2
$ echo $((3 + $(echo 4)))
7
$ a=3
$ echo $((a + $(echo 4)))
7
# undefine a
$ a=
$ echo $((a + $(echo 4)))
4
$ a="Hello world"
$ echo $((a + 1))
1
# undefine a again
$ a=
$ echo $(($(echo $a)))
0