Question

I am trying to figure out why bash "miss-behaves":

REG=true 
VIN=false

if $REG -a $VIN; then
    echo $REG $VIN
fi

when run, it yields:

$ bash test.sh 
true false

I was expecting nothing, can you show how to make a complete evaluation of both variables ?

Was it helpful?

Solution 2

Use && instead in the most POSIX way:

if [[ "$REG" && "$VIN" ]]; then
    echo $REG $VIN
fi

If you want to use the -a, then surround with brackets:

if [ "$REG" -a "$VIN" ]; then

if $REG && $VIN; then

OTHER TIPS

In REG=true, 'true' is a string. When you do $REG, you're executing the command true.

if $REG -a $VIN means "run the command true with the option '-a' and argument '$VIN', which are ignored by true. So it's the same as if you had if true.

if $REG && $VIN causes 'true' and 'false' to be executed and their results 'and-ed', which yields false.

if [ "$REG" -a "$VIN" ] DOES NOT WORK (as defined here). This is the same as if test "true" -a "false". Any non-null string is true, so this statement is true. Same goes for if [[ "$REG" && "$VIN" ]]

However:

if [[ `$REG` && `$VIN` ]] # works

does work because here you execute the commands true and false.

Correct way for you would be:

if [[ $REG = 'true' && $VIN = 'true' ]]; then
    echo "$REG $VIN"
fi

This is the most correct and safe way (unlike executing your $REG and $VIN as other answers suggest). For example, what is going to happen if $REG variable is empty? Or what if it equals to something different than just true or false?

If you want boolean behavior in bash, then consider the fact that empty strings are falsy.

REG=1
if [[ $REG ]]; then
    echo '$REG is true!'
fi

or like that for multiple variables:

REG=1
VIN=''

if [[ $REG && $VIN ]]; then
    echo '$REG and $VIN are true!'
fi
if [[ $REG && ! $VIN ]]; then
    echo '$REG is true and $VIN is false!'
fi

So, if you want something to be false, then either leave it unset or use an empty string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top