Reputation: 159
I'm trying to create a script which will only continue when pinging is unresponsive.
I'm running into 2 main issues. One being that it will require 2 CTL-C commands to end the script, and the other issue being that the script will never end and will need killing.
Here are my attempts;
rc=0
until [ $rc -gt 0 ]
do
ping 69.69.69.69 > /dev/null 2>&1
rc=$?
done
## Here will be the rest of code to be executed
I feel this one above is very close as it requires the 2 CTL-C commands and continues. Here is something I found on SO but can't get to work at all.
counter=0
while [ true ]
do
ping -c 1 69.69.69.69 > /dev/null 2>&1
if [ $? -ne 0 ] then
let "counter +=1"
else
let "counter = 0"
fi
if [ $counter -eq 10 ] then
echo "Here should be executed once pinging is down"
fi
done
Any assistance is greatly appreciated, Thank you.
Upvotes: 0
Views: 3555
Reputation: 743
There's a few issues with that: Firstly the if statements are wrong Use this format
if [ $? -ne 0 ] then;
or this other format
if [ $? -ne 0 ]
then
Secondly I suspect that your pings are not timing out
ping -c 1 -w 2 69.69.69.69 > /dev/null 2>&1
might be helpfull
Thirdly your loop will continue incrementing counter even after 10. You might want to quit after 10
while [ $counter -le 10 ]
If you would be happy with executing something if ping times out after x seconds without any response it could be all condensed (ten seconds in the example below):
ping -c 1 -w 10 69.69.69.69 >/dev/null 2>&1 || echo "run if ping timedout without any response"
Upvotes: 1
Reputation: 59416
Try this:
while ping -c 1 -W 20 "$host" >& /dev/null
do
echo "Host reachable"
sleep 10 # do not ping too often
done
echo "Host unreachable within 20 seconds"
Upvotes: 3