Understanding boolean operators in bash script
The variable $phone_missing
is a string that happens to contain false
. And a non-empty string evaluates to true
.
See also http://www.linuxintro.org/wiki/Babe#empty_strings
I often use "true" and "false" since they are also commands that merely return success and failure respectively. Then you can do
if "$phone_missing"; then ...
Here's one way to do this, while retaining the true/false values.
phone_missing=false
if [ "$phone_missing" != false ]; then
echo "phone_missing is not 'false' (but may be non-true, too)"
fi
if [ "$phone_missing" == true ]; then
echo "phone_missing is true."
fi
The double quotes around $phone_missing
are to protect against the case where variable phone_missing
is not defined at all. Another common idiom to ward against this is [ x$phone_missing != xfalse ]
, but the quotes seem more natural to me.
The hint is in the bash
help page for test
:
STRING True if string is not empty. ... ! EXPR True if expr is false.
So, basically [ $foo ]
will be true if $foo
is non-empty. Not true or false, just non-empty. [ ! $foo ]
is true if $foo is empty or undefined.
You could always change your code to just set phone_missing
to a non-empty value, which will denote true. If phone_missing
is unset (or empty — phone_missing=""
), it will be false. Otherwise, you should be using the string testing operators (=
and !=
).
The other slight issue is the assignment. You have it as $phone_missing=true
, whereas it should be phone_missing=true
(no dollar sign).
Sorry if this is a bit dense, it's because I am. It's been a long day. :)