Long ago, when all we had was sh
, booleansBooleans where handled by relying on a convention of the test
program where test
returns a false exit status if run with nowithout any arguments. This
This allows one to think of a variable that is unset as false and variable set to any value as true. TodayToday, test is builtin to bashtest
is a builtin to Bash and is commonly known by its one character-character alias [
(or an executable to use in shells lacking it, as dolmen notes):
FLAG="up or <set>"
if [ "$FLAG" ] ; then
echo 'Is true'
else
echo 'Is false'
fi
# unsetUnset FLAG
# also works
FLAG=
if [ "$FLAG" ] ; then
echo 'Continues true'
else
echo 'Turned false'
fi
Because of quoting conventions, script writers prefer to use the compound command [[
that mimics test
, but has a nicer syntax: variablesvariables with spaces do not need to be quoted,quoted; one can use &&
and ||
as logical operators with weird precedence, and there are no POSIX limitations on the number of terms.
For example, to determine if FLAG is set and COUNT is a number greater than 1:
FLAG="u p"
COUNT=3
if [[ $FLAG && $COUNT -gt '1' ]] ; then
echo 'Flag up, count bigger than 1'
else
echo 'Nope'
fi
This stuff can get confusingThis stuff can get confusing when spaces, zero length strings, and null variables are all needed and also when your script needs to work with several shells.