Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm trying to write a Bash script that is aware of internet connectivity.

How can I achieve that?

For example:

if (something that checks internet connection);then
curl -o new someurl
else 
exit 1
share|improve this question

2 Answers 2

up vote 3 down vote accepted

Try using the curl command and checking the exit status in an if statement.

curl -D- -o /dev/null -s http://www.google.com
if [[ $? == 0 ]]; then
  foocode
else
  exit 1
fi
share|improve this answer

I was using snmp when I had a router that support it to get the ip assigned to the Wan interface (.253 was the router addr):

IP=$(/usr/bin/snmpwalk -v2c -Ov -cpublic 192.168.1.253 \
          IP-MIB::ipAdEntAddr 2>/dev/null \
          | /bin/grep -v "0.0.0.0\|127.0.0.1\|192.168.1.253")

Or maybe you could webscarp it from the router's stat pages with curl.

Currently instead I use to check/get the ip from the service I use for the dynamic dns:

IP=$(curl -s 'http://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/\1/g')

and then:

if [ "$IP" != "" ] && [ "$IP" != "0.0.0.0" ]; then
   # connected
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.