I want to display "Unit 1 is online" or "Unit 1 is offline" based on ping test in Shell Script. However, I can't find a flag or a way to extract text from the output of the ping test so as to use it with an if-case statement to get the desired output.
read -p "Enter the number of Units: " x
for ((i=1; i<=$x; i++))
do
ping -c1 a.b.c."$i"
if ping=success
echo "Unit "$i" is online"
else
echo "Unit "$i" is offline"
fi
done
If you are using the standard GNU/Linux ping
tool, then the manual states:
If ping does not receive any reply packets at all it will exit with code 1. If a packet count and deadline are both specified, and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code to see if a host is alive or not.
This means you can capture the exit code from the command in the shell and switch on that. For bash:
if ping -c1 192.168.1."$i" ; then
echo "Unit ${i} is online"
else
echo "Unit ${i} is offline"
fi
Or as a one-liner using ||
and &&
:
ping -c 192.168.1."$i" && echo "Unit ${i} is online" || echo "Unit ${i} is offline"