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?
I can think of a one liner like this to run
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:
and this
Ping returns different exit codes depending on the type of error.
0 means host reachable
2 means unreachable
You don't need the backticks in the if statement. You can use this check
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.
FYI, I just did some test using the method above and if we use multi ping (10 requests)
the result of multi ping command will be "0" if at least one of ping result reachable, and "1" in case where all ping requests are unreachable.
There is advanced version of ping - "fping", which gives possibility to define the timeout in milliseconds.