Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

Why does bash have the following behavior?

echo $((true == false)) 1 

I would have thought that this would print 0, but it prints 1.

This is further complicated by the following facts:

> echo $((true)) 0 > echo $((false)) 0 > echo $((true == true)) 1 > echo $((false == false)) 1 
like image 599
HaskellElephant Avatar asked Dec 20 '11 17:12

HaskellElephant


1 Answers

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.

like image 115
zostay Avatar answered Sep 19 '22 13:09

zostay