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 1:

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

Solution 2:

You don't need the backticks in the if statement. You can use this check

if ping -c 1 some_ip_here &> /dev/null
then
  echo 1
else
  echo 0
fi

The if command checks the exit code of the following command (the ping). If the exit code is zero (which means that the command exited successfully) the then block will be executed. If it return a non-zero exit code, then the else block will be executed.

Solution 3:

I can think of a one liner like this to run

ping -c 1 127.0.0.1 &> /dev/null && echo success || echo fail

Replace 127.0.0.1 with IP or hostname, replace echo commands with what needs to be done in either case.

Code above will succeed, maybe try with an IP or hostname you know that is not accessible.

Like this:

ping -c 1 google.com &> /dev/null && echo success || echo fail

and this

ping -c 1 lolcatz.ninja &> /dev/null && echo success || echo fail

Solution 4:

There is advanced version of ping - "fping", which gives possibility to define the timeout in milliseconds.

#!/bin/bash
IP='192.168.1.1'
fping -c1 -t300 $IP 2>/dev/null 1>/dev/null
if [ "$?" = 0 ]
then
  echo "Host found"
else
  echo "Host not found"
fi