Locane
Locane

Reputation: 3134

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?

Upvotes: 1

Views: 247

Answers (1)

chepner
chepner

Reputation: 531275

You aren't checking the exit code of ping; you are checking if it wrote anything to standard output. You code is equivalent to

if [[ -n $(ping -c 1 254.254.254.254) ]]; then

and $? is the exit code of [[ ... ]] (which is why you ended up in the "Yes" branch in the first place).

To check the exit code, don't capture the output, and don't use it inside a [[ ... ]] command.

if ping -c 1 254.254.254.254; then

Upvotes: 4

Related Questions