dimanche 8 avril 2018

Bash if - Exit code shows 0 when it shouldn't?

I couldn't find this question anywhere - please let me know if it's a duplicate.

I'm trying to figure out why the exit code ($?) is 0 in this Bash if statement, when 254.254.254.254 obviously doesn't exist:

if [[ `ping -c 1 254.254.254.254` ]];then
  echo "Yes - $?"
else
  echo "No - $?"
fi

Yes - 0

After experimenting with if [[ ` ` ]] a little bit, it looks like it's evaluating true if there is ever any output on stdout, whether the output was desired or not, whether an error was returned or not. I'd thought that testing for exit code $? would alleviate that problem, but apparently not?

If you run ping -c 1 254.254.254.254;echo $? you'll get the proper exit code, 1. Why doesn't that show up in my if statement?

Aucun commentaire:

Enregistrer un commentaire