ping -c 1 127.0.0.1 &> /dev/null && echo success || echo fail
ping -c 1 127.0.0.1 ; echo $?
# 0
ping -c 1 192.168.1.5 ; echo $?
# 2
0 means host reachable
1 Destination Host Unreachable
2 means unreachable
if ping -c 1 some_ip_here &> /dev/null
then
echo 1
else
echo 0
fi
There is advanced version of ping - "fping", which gives possibility to define the timeout in milliseconds.
#!/bin/bash
IP='192.168.1.1'
sudo ping -c1 -t 200 $IP 2>/dev/null 1>/dev/null
if [ "$?" = 0 ]
then
echo "Host found"
else
echo "Host not found"
fi
This is a complete bash script which pings target every 5 seconds and logs errors to a file.
Enjoy!
#!/bin/bash
FILE=errors.txt
TARGET=192.168.0.1
touch $FILE
while true;
do
DATE=$(date '+%d/%m/%Y %H:%M:%S')
ping -c 1 $TARGET &> /dev/null
if [[ $? -ne 0 ]]; then
echo "ERROR "$DATE
echo $DATE >> $FILE
else
echo "OK "$DATE
fi
sleep 5
done
for i in `cat Hostlist`
do
ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done