A Quick and Dirty "It's Back Up" Bash Script

Today, I had a client’s T1 line go down. Unfortunately, FairPoint Communications has had a mixed track record when it comes to telling us that they have (or more often, have not) fixed the issues.
So I wrote a simple bash script to ping the IP address of the router on the down T1 line, and email me when it came back up. Think of this as the ultra-poor man’s Nagios.
#!/bin/sh
ping -c 1
example.com
while [ $? != 0 ]; do
ping -c 1
example.com
done
echo "
Example.com is up if you are reading this." | \
mail
[email protected] -s "example.com is back up!";
exit

  1. The first line specifies what shell to run this script with (in this case, /bin/sh).
  2. The second line pings the currently down host (example.com) with 1 packet.
  3. The third line starts the while loop, and continues it as long as ping returns something other than a 0 (which indicates success).
  4. The fourth line pings the host again.
  5. The fifth line ends the loop, but only if ping succeeded (i.e. the host is up again).
  6. The sixth
  7. & seventh line emails [email protected] to let me know the host is back up.
  8. Finally, the eighth line exits.

Note that you have to have a working “mail” program in your path for this to work. If not, there are other options (touching a file, curling a URL, etc., but that’s beyond the scope of this example.

Leave a Reply