Setting
To set a bash variable $subject
to boolean true
or false
, use subject=true
or subject=false
.
To set a vash variable to null, use subject=
or subject=$()
or unset subject
Testing
The use of single brackets and no brackets is suspicious and I've found several discrepancies in the expected behavior around how empty strings, null values, and integer 0 and 1 are evaluated.
First, defining the correct behavior of a strict boolean test as follows:
- The
if
test for boolean true
evaluates to true only when the subject is boolean true. Such a test will evaluate to false for any other value, including 1
and any string with value 'true'
- The
if
test for false
evaluates to true only when the subject is boolean false. Such a test will evaluate to false for any other value, including 0
, null
, and an empty string ''
The correct method to accomplish this is to use double square brackets and explicitly test against true
or false
as follows:
if [[ ${subject} = true ]]; then { ... } fi # only if boolean true
if [[ ${subject} = false ]]; then { ... } fi # only if boolean false
Note that if you use such a test for boolean true (or false), an else
block will not only cover the opposite condition, but also the entire set of possible values that are not boolean false
(or true
) respectively.