I'm thinking that this needs to be changed to a while clause, at the moment it'll wait till all 10000 pings are done, I need it to return when the ping is successful. The program "say" is on OSX it makes the computer speak.
#!/bin/bash
echo begin ping
if ping -c 100000 8.8.8.8 | grep timeout;
then echo `say timeout`;
else echo `say the internet is back up`;
fi
OK I don't have rights to answer my own question so here's my answer for it after playing around:
Thanks, yeah I didn't know about $? until now. Anyway now I've gone and made this. I like that yours doesn't go forever but in my situation I didn't need it to stop until it's finished.
#!/bin/bash
intertube=0
echo "begin ping"
while [ $intertube -ne 1 ]; do
ping -c 3 google.com
if [ $? -eq 0 ]; then
echo "ping success";
say success
intertube=1;
else
echo "fail ping"
fi
done
echo "fin script"
I liked paxdiablo's script, but wanted a version that ran indefinitely. This version runs ping until a connection is established and then prints a message saying so.
I also have a Gist of this script which I'll update with fixes and improvements as needed.
You don't need to use echo or grep. You could do this:
If you use the
-o
option, Mac OS X’sping
will exit after receiving one reply packet.Further reading: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man8/ping.8.html
EDIT: paxdiablo makes a very good point about using
ping
’s exit status to your advantage. I would do something like:ping
will send up to 100,000 packets and then exit with a failure status—unless it receives one reply packet, in which case it exits with a success status. Theif
will then execute the appropriate statement.Here's my one-liner solution:
This runs an infinite ping in a new screen session until there is a response, at which point it sends an e-mail to
my-email@example.com
. Useful in the age of e-mail sent to phones.(You might want to check that
mail
is configured correctly by just runningecho test | mail -s test my-email@example.com
first. Of course you can do whatever you want fromdone;
onwards, sound a bell, start a web browser, use your imagination.)You probably shouldn't rely on textual output of a command to decide this, especially when the
ping
command gives you a perfectly good return value:In other words, use something like:
I use this Bash script to test the internet status every minute on OSX