I have defined the following variable:
myVar=true
now I’d like to run something along the lines of this:
if [ myVar ]
then
echo "true"
else
echo "false"
fi
The above code does work, but if I try to set
myVar=false
it will still output true.
What might be the problem?
edit: I know I can do something of the form
if [ "$myVar" = "true" ]; then ...
but it is kinda awkward.
Thanks
bash doesn’t know boolean variables, nor does
test(which is what gets called when you use[).A solution would be:
because
trueandfalseare commands that return0or1respectively which is whatifexpects.Note that the values are “swapped”. The command after
ifmust return0on success while0means “false” in most programming languages.SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can’t contain malicious code like
rm -rf /