How to evaluate boolean variable in if block in bash?

I defined the following variable:

myVar=true 

now I would like to run something line by line:

 if [ myVar ] then echo "true" else echo "false" fi 

The above code really works, but if I try to install

 myVar=false 

it will return true anyway. What could be the problem?

edit: I know I can do something like form

 if [ "$myVar" = "true" ]; then ... 

but it’s awkward.

thank

+54
bash
Sep 28 2018-10-09T00:
source share
2 answers

bash does not know boolean variables, nor test (this is what gets called when using [ ).

Decision:

 if $myVar ; then ... ; fi 

because true and false are commands that return 0 or 1 respectively, as expected by if .

Please note that the values ​​are "replaced". The command after if should return 0 on success, and 0 means false in most programming languages.

SAFETY WARNING . This works because BASH expands the variable, then tries to execute the result as a command! Make sure that the variable cannot contain malicious code, for example rm -rf /

+89
Sep 28 '10 at 8:01
source share
β€” -

Note that the constructor if $myVar; then ... ;fi if $myVar; then ... ;fi has a security issue that you can avoid with

 case $myvar in (true) echo "is true";; (false) echo "is false";; (rm -rf*) echo "I just dodged a bullet";; esac 

You may also need to rethink why if [ "$myvar" = "true" ] seems uncomfortable. This is a string comparison in the shell, which perhaps allows the process to be processed only to obtain exit status. A fork is a difficult and expensive operation, while comparing nobody's is cheap. Think of several processor cycles versus several thousand. My case solution is also being processed without forks.

+32
Jan 24 '13 at 15:06
source share



All Articles