Bash Boolean testing Bash Boolean testing bash bash

Bash Boolean testing


Without any operators, [[ only checks if the variable is empty. If it is, then it is considered false, otherwise it is considered true. The contents of the variables do not matter.


Your understanding of booleans in shell context is incorrect.

var1=truevar2=false

Both the above variables are true since those are non-empty strings.

You could instead make use of arithmetic context:

$ a=1$ b=0$ ((a==1 && b==0)) && echo yy$ ((a==0 && b==0)) && echo y$$ ((a && !(b))) && echo y;       # This seems to be analogous to what you were attemptingy


The shell does not have Boolean variables, per se. However, there are commands named true and false whose exit statuses are 0 and 1, respectively, and so can be used similarly to Boolean values.

var1=truevar2=falseif $var1 && ! $var2; then var2="something"; fi

The difference is that instead of testing if var1 is set to a true value, you expand it to the name of a command, which runs and succeeds. Likewise, var2 is expanded to a command name which runs and fails, but because it is prefixed with ! the exit status is inverted to indicate success.

(Note that unlike most programming languages, an exit status of 0 indicates success because while most commands have 1 way to succeed, there are many different ways they could fail, so different non-zero values can be assigned different meanings.)