Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to (more or less) reliably check if the Internet is up

I need a Bash (or a plain shell) script to put in a cronjob that every minute checks if the Internet is up.

This is how I did it:

#! /bin/sh

host1=google.com
host2=wikipedia.org
curr_date=`date +"%Y%m%d%H%M"`

echo -n "${curr_date};"
((ping -w5 -c3 $host1 || ping -w5 -c3 $host2) > /dev/null 2>&1) && 
echo "up" || (echo "down" && exit 1)

How would you do it? Which hosts would you ping?

Clarifications:

  • By "internet is up", I mean my internet connection.

  • By "up", I mean to have usable connection (doesn't really matter if we are talking about the DNS being down or the connection is really really slow [mind the -w for timeout]). That is also why I didn't include any IP but only hosts.

Should I also ping Stack Overflow? I mean, if I can't access Google, Wikipedia or Stack Overflow, I don't want Internet :p

like image 479
João Portela Avatar asked May 27 '10 15:05

João Portela


2 Answers

That one seems like a good solution. Just add a few more hosts, and maybe some pure IP hosts so you don't rely on DNS functioning (which in itself depends on your definition of "up").

like image 176
Emil Vikström Avatar answered Oct 06 '22 23:10

Emil Vikström


Thanks for your code, it works great, I've left only one line actually:

((ping -w5 -c3 8.8.8.8 || ping -w5 -c3 4.2.2.1) > /dev/null 2>&1) && echo "up" || (echo "down" && exit 1)
like image 45
Radamanf Avatar answered Oct 07 '22 00:10

Radamanf