Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evaluate a boolean variable in an if block in bash? [duplicate]

Tags:

bash

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

like image 722
devoured elysium Avatar asked Sep 28 '10 07:09

devoured elysium


People also ask

How do you use Booleans in bash?

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.

Is 1 true or false in bash?

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.

Does bash have boolean variables?

Bash does not support Boolean values, but any bash variable can contain 0 or “true” and 1 or “false“.

How do you negate a variable in bash?

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.


1 Answers

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 /

like image 134
Aaron Digulla Avatar answered Sep 25 '22 17:09

Aaron Digulla