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

后端 未结 3 1763
广开言路
广开言路 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:03

    All the posters talking about 0 being true and 1 being false have missed the point. In this case, 1 is true and 0 is false in the usual boolean sense because of the arithmetic evaluation context caused by $(()).

    The == operation inside of $(()) is not equality of return statuses in Bash, it performs numeric equality using the literals given where "false" and "true" are treated as variable, but have not yet been bound, which both are interpreted as 0 since they have no value yet assigned:

    $ echo $((true))
    0
    $ echo $((false))
    0
    

    If you want to compare the return status of true and false you want something like:

    true
    TRUE=$?
    false
    FALSE=$?
    if (( $TRUE == $FALSE )); then echo TRUE; else echo FALSE; fi
    

    But, I'm not sure why you would want to do this.

    EDIT: Corrected the part in the original answer about "true" and "false" being interpreted as strings. They are not. They are treated as variables, but have no value bound to them yet.

提交回复
热议问题