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
There are no Booleans in Bash Bash does have Boolean expressions in terms of comparison and conditions. That said, what you can declare and compare in Bash are strings and numbers. That's it. Wherever you see true or false in Bash, it's either a string or a command/builtin which is only used for its exit code.
There are no Booleans in Bash. However, we can define the shell variable having value as 0 (“ False “) or 1 (“ True “) as per our needs. However, Bash also supports Boolean expression conditions.
Bash does not support Boolean values, but any bash variable can contain 0 or “true” and 1 or “false“.
Bash does not have the concept of boolean values for variables. The values of its variables are always strings. They can be handled as numbers in some contexts but that's all it can do. You can use 1 and 0 instead or you can compare them (with = or == ) as strings with true and false and pretend they are boolean.
bash doesn't know boolean variables, nor does test
(which is what gets called when you use [
).
A solution would be:
if $myVar ; then ... ; fi
because true
and false
are commands that return 0
or 1
respectively which is what if
expects.
Note that the values are "swapped". The command after if
must return 0
on success while 0
means "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 /
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With