mardi 17 décembre 2019

What's wrong with `if [ #? -ne 0 ]` to check for command failure (shellcheck.net)?

I upload my script to the shellcheck.net and I got this recommendation (SC2181) below:

Problematic code:

make mytarget

if [ $? -ne 0 ]
then
  echo "Build failed"
fi

Correct code:

if ! make mytarget
then
  echo "Build failed"
fi

What's wrong with if [ #? -ne 0 ]? I tried with ! make mytarget, but not always get the result that I exactly wanted...

My script has the line of codes like below:

ffmpeg -h > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "FFmpeg NOT INSTALLED"
.
.
.
fi

I tried this and it worked, my bad:

if ! (ffmpeg -h > /dev/null 2>&1)
then
    echo "FFmpeg NOT INSTALLED"
.
.
.
fi

Aucun commentaire:

Enregistrer un commentaire