tags:

views:

20

answers:

2

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 ode 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

+2  A: 

bash doesn't know boolean variables, nor does test (which is what gets called when you use [).

A solution would be:

if $myVar ; then ...

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.

Aaron Digulla
+1 for beating me to the punch, and with a good explanation too :-)
Tony
+1  A: 
if $myVar; then...
Tony