Why does $((true == false)) evaluate to 1 in bash?

后端 未结 3 1761
广开言路
广开言路 2021-02-03 17:28

Why does bash have the following behavior?

echo $((true == false))
1

I would have thought that this wou

3条回答
  •  生来不讨喜
    2021-02-03 18:06

    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
    

提交回复
热议问题