I have data loggers spread around the solar power system, and a single program that runs at midnight to collect the day's data and put it on a hard drive.
The bash script on the Ubuntu server steps through 7 Raspbian units that have the data collected and puts it in the proper place on the hard drive, in directories named by the units out there. I figured out how to take the generic names today.dat and today.png and save them with the day's date in the archive like 2017-08-10.png and 2017-08-10.dat
--> Occasionally one of the units will not respond due to some problem or other, and it blocks execution of the program.
So I would like to use ping to test whether the system responds before I decide whether to try to gather data from it.
My system names are all in the /etc/hosts file so I reference them by name.
For purposes of this question I am checking SOLAR - the one that monitors the charge controller and inverter behavior.
Here is what I have tried:
if $( ping -c 1 SOLAR | grep icmp* | wc -l ) eq 0
then
(do stuff like ssh -e "gnuplot makepng" then scp the png and raw data)
fi
(too complicated)
and
if [ $(ping -c 1 SOLAR >/dev/null) eq 0 ]
then do the stuff
fi
(looks OK but I don't understand the need for the square brackets)
There must be a better way.
I am hoping to do something more like
if $(ping -c 1 SOLAR) eq 0
then
(do stuff)
else
(then maybe echo "SOLAR didn't respond" | ssmtp [email protected]
fi
I haven't programmed bash in a couple of decades - used C shell most of the time. And I am getting way too much varying advice all over the net about the best way to do this.
So can anybody please suggest a simple way to do this?
It seems you are only interested in the exit status of
ping
i.e. whether you are getting ICMP ECHO_RESPONSE from the host to your ECHO_REQUEST; you can just doping -c 1 ...
andping
would exit with status0
if the host is sending response,1
if no response and2
for unknown host.You can easily use this with
if
construct; you don't need to count response, just useping
asif
's condition asif
would evaluate the exit status ofping
to proceed to any defined branch:I am redirecting
ping
's STDOUT and STDERR streams to/dev/null
as we are not interested in those.