mercredi 27 janvier 2016

Strange Bash if/elif behavior

I have the following script:

_eliftest.sh__

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?

Aucun commentaire:

Enregistrer un commentaire