Search code examples
bashshellif-statementpingdev-null

Omit error from shell script output


I'd like to omit the error from this IF statement if ICMP echo fails.

Example code:

if ping -q -c 1 -W 1 1.2.3.4 >/dev/null; then
  echo -e "PING OK"
else
  echo -e "PING NOK"
fi

It works perfectly if the ping is successful or you run the command outside of a script, but gives the below output if there is no response.

PING 1.2.3.4 (1.2.3.4): 56 data bytes

--- 1.2.3.4 ping statistics ---
1 packets transmitted, 0 packets received, 100.0% packet loss
PING NOK

I've seen answers for this out there quoting 2>/dev/null, but this then displays the entire ping query in the output, whether successful or not! Example with 2>/dev/null as below.

PING 1.2.3.4 (1.2.3.4): 56 data bytes

--- 1.2.3.4 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 26.134/26.134/26.134/0.000 ms
PING OK

This is a bit of a n00b question, but I'm a networking chap, not a developer :)

Thanks in advance!!


Solution

  • The «classic» solution:

    if ping -q -c 1 -W 1 1.2.3.4 >/dev/null 2>&1; then
      echo -e "PING OK"
    else
      echo -e "PING NOK"
    fi
    

    A somewhat more modern (and not POSIX-compliant!) approach, available since BASH 4:

    if ping -q -c 1 -W 1 1.2.3.4 &>/dev/null; then
      echo -e "PING OK"
    else
      echo -e "PING NOK"
    fi
    

    Both of these mean «redirect both STDOUT and STDERR to /dev/null», but the first one does it sequentially, first redirecting STDOUT and then redirecting STDERR to STDOUT.