Why is $ ((true = false)) evaluated to 1 in bash?

Why does bash have the following behavior?

echo $((true == false)) 1 

I would have thought it would print 0 , but print 1 .

This is further complicated by the following facts:

 > echo $((true)) 0 > echo $((false)) 0 > echo $((true == true)) 1 > echo $((false == false)) 1 
+46
bash
Dec 20 '11 at 17:24
source share
4 answers

All posters talking about 0 are true, and 1 - false, missed the point. In this case, 1 is true, and 0 is false in the usual Boolean sense due to the context of evaluating arithmetic caused by $(()) .

The == operation inside $(()) not an equality of return statuses in Bash, it performs numerical equality using literals where "false" and "true" are considered as variables, but they have not been interpreted as 0 yet, since they are still not assigned:

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

If you want to compare the return status 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 like to do this.

EDIT: Fixed part of the original answer stating that "true" and "false" are interpreted as strings. They are not. They are considered as variables, but not yet tied to them.

+56
Dec 20 '11 at 17:37
source share

Ok, so it seems that there is a lot of confusion as to what $((...)) really does.

It performs arithmetic evaluation of its operands , words , not commands or string literals (i.e. true really $true )) and nothing that is not a number 0 . The == operator compares two numbers and returns 1 if they are equal.

That's why $((true == false)) is 1: there are no environment variables true or false in the environment, which means that $true and $false evaluate the empty string, so 0 in an arithmetic context!

To be complete, you can also use command substitution in an arithmetic context ... For example:

 $ 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 
+21
Dec 20 2018-11-21T00:
source share
 $ bash --version GNU bash, version 3.2.53(1)-release (x86_64-apple-darwin13) $ true="true" $ unset false $ if [[ $true ]] ; then echo hi ; fi hi $ if [[ $false ]] ; then echo hi ; fi $ if [[ $true || $false ]] ; then echo hi ; fi hi $ if [[ $false || $true ]] ; then echo hi ; fi hi $ if [[ $false && $true ]] ; then echo hi ; fi $ if [[ $true && $false ]] ; then echo hi ; fi $ if [[ $true == $false ]] ; then echo hi ; fi $ if [[ $true == $true ]] ; then echo hi ; fi hi $ if [[ $false == $false ]] ; then echo hi ; fi hi` 
-one
Nov 06
source share

Because in bash, the value 0 is true, and everything except 0 is false.

-2
Dec 20 '11 at 17:28
source share



All Articles