Reputation: 81
I'm just trying to write a small script to see whether or not certain IP addresses are online as a link to an idea I had, I don't know much bash at all but I was wondering if anyone could help me out. It was to have an IP address pinged 2 times and if the results are say
--- 127.0.0.1 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms
I would like it to echo "OFFLINE"
and go onto pinging the next IP address, and if the results are say
--- 127.0.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
I would like it to echo "ONLINE"
and continue onto the next IP address.
So is there any way to take the output of the ping and use it to determine what is echoed?
Upvotes: 1
Views: 2575
Reputation: 14520
You can use ping
's exit status. It will return 0
(i.e., success) if it is able to ping the target, and 1 otherwise. So you could do
if ping -c 2 -q host1 &>/dev/null; then
echo "ONLINE"
else
echo "OFFLINE"
fi
but if you want to capture the output of a command you can use command substitution like
ping_output="$(ping -c2 host1)"
where the output of the command inside $(...)
will be saved in the variable, here named ping_output
or if you wanted to use grep
to see if the string appeared in the output you could pipe it:
if ping -c 2 host1 | grep -q " 0% packet loss"; then
echo ONLINE
else
echo OFFLINE
fi
we use -q
to grep so it won't print the line that matches
Upvotes: 3