简体   繁体   中英

Strange Bash if/elif behavior

I have the following script:

a=$1
b=$2

if [ ! a ]; then
    echo "a=$a"
elif [ b ]; then
    echo "b=$b"
fi

This is the four possible ways I can call it:

balter$ bash eliftest.sh true true
b=true
balter$ bash eliftest.sh true false
b=false
balter$ bash eliftest.sh false true
b=true
balter$ bash eliftest.sh false false
b=false

I would have expected:

b=true # !a evaluates to false but b is true
<nothing> # !a evaluates to false and b is also false
a=false # !a evaluates to true and if short circuits 
a=false # !a evaluates to true and if short circuits

I clearly don't understand bash elif statements. Can someone enlighten me?

Also, one the interwebs, bash scripting tutorials sometimes use [[...]] but mostly [...] . I see a lot of SO commenters saying that you should use [[...]] . Is there a rule of thumb for when one is better than the other?

You are making two mistakes:

  1. you want to use the variable a , and not the character "a"; so use $a .
  2. Since bash doesn't know booleans, you might just check if the value is "true".

So you want something like this:

if [ "$a" = "true" ]; then
    echo "a=$a"
elif [ "$b" = "true" ]; then
    echo "b=$b"
fi

I implemented two more recommendations:

  • always put variables between quotes; to avoid errors when they are empty ("$a" instead of $a)
  • use only one = sign for portability (as suggested by @tripleee)

some more detaills

bash doesn't know boolean values. Your test:

if [ ! a ];

will always fail since you ask bash: is the character "a" empty? Which is the same as:

if [ "" = "a" ]

suppose you did use $a (the variable):

if [  ! $a ] 

this would still always be false; since this is equivalent to:

if [ "" = "$a" ]

which will never be true whether a=true or a=false (since a is never an empty string)

Avoid the brackets. Try this:

a=$1
b=$2
if ! $a 
then
    echo "a=$a"
elif $b 
then
    echo "b=$b"
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM