Skip to main content

Simple flag based comparison in Linux [Resolved]

I am trying to run a simple script to check for a flag and then check for additional conditions. The following always echoes "Run Script.." irrespective of the value of the flag:

FLAG_Control=false
if [ $FLAG_Control ] && [ -d /path/to/dir ];then
    echo "Run script.."
fi

while this works as expected:

FLAG_Control=false
if [ $FLAG_Control = true ] && [ -d /path/to/dir ];then
    echo "Run script.."
fi

Does this mean that I have to do an explicit comparison? Am I doing something wrong in the first one?


Question Credit: techiebong
Question Reference
Asked April 5, 2019
Tags: linux
Posted Under: Unix Linux
76 views
3 Answers

I have been learning bash scripting over the past few months. What I have learned is that there are no boolean variables in bash. However, that isn't to say there aren't any boolean values.

If/then looks for 1 or 0. Now.... here's the caveat: 0 is true and everything else is false. For example, when you check to see if a directly exists the result comes back as 0 not 1.

If you get any sort of error code from the function you call, you can trap for that error.

So, try this instead:

FLAG_Control=1
if [ $FLAG_Control ] && [ -d /path/to/dir ];then
   echo "Run script.."
fi

credit: Rui F Ribeiro
Answered April 5, 2019

The nearest thing to a true value for a shell a variable is a set value. There are some native parameter properties that depend on it as well. For example:

FLAG=
[ -d "${FLAG:+$HOME}" ] || ! echo \
either \$HOME is not a directory or \$FLAG is null or unset

Above $FLAG conditionally expands to the value of $HOME only if it is set and not null. There are several variations on this, but the overall gist is that the parameter's value is not always quite so important as whether the parameter has a value. Setting FLAG to any value at all above would result in a true return from test rather than a failure.


credit: mikeserv
Answered April 5, 2019
Your Answer