bashnetwork-programmingpingconnectivity

Checking host availability by using ping in bash scripts


I want to write a script, that would keep checking if any of the devices in network, that should be online all day long, are really online. I tried to use ping, but

if [ "`ping -c 1 some_ip_here`" ]
then
  echo 1
else
  echo 0
fi

gives 1 no matter if I enter valid or invalid ip address. How can I check if a specific address (or better any of devices from list of ip addresses) went offline?


Solution

  • Ping returns different exit codes depending on the type of error.

    ping 256.256.256.256 ; echo $?
    # 68
    
    ping -c 1 127.0.0.1 ; echo $?
    # 0
    
    ping -c 1 192.168.1.5 ; echo $?
    # 2
    

    0 means host reachable

    2 means unreachable