How to test an Internet connection with bash? How to test an Internet connection with bash? bash bash

How to test an Internet connection with bash?


Without ping

#!/bin/bashwget -q --spider http://google.comif [ $? -eq 0 ]; then    echo "Online"else    echo "Offline"fi

-q : Silence mode

--spider : don't get, just check page availability

$? : shell return code

0 : shell "All OK" code

Without wget

#!/bin/bashecho -e "GET http://google.com HTTP/1.0\n\n" | nc google.com 80 > /dev/null 2>&1if [ $? -eq 0 ]; then    echo "Online"else    echo "Offline"fi


Ping your default gateway:

#!/bin/bashping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && echo ok || echo error


Super Thanks to user somedrew for their post here: https://bbs.archlinux.org/viewtopic.php?id=55485 on 2008-09-20 02:09:48

Looking in /sys/class/net should be one way

Here's my script to test for a network connection other than the loop back.I use the below in another script that I have for periodically testing if my website is accessible. If it's NOT accessible a popup window alerts me to a problem.

The script below prevents me from receiving popup messages every five minutes whenever my laptop is not connected to the network.

#!/usr/bin/bash# Test for network conectionfor interface in $(ls /sys/class/net/ | grep -v lo);do  if [[ $(cat /sys/class/net/$interface/carrier) = 1 ]]; then OnLine=1; fidoneif ! [ $OnLine ]; then echo "Not Online" > /dev/stderr; exit; fi

Note for those new to bash: The final 'if' statement tests if NOT [!] online and exits if this is the case. See man bash and search for "Expressions may be combined" for more details.

P.S. I feel ping is not the best thing to use here because it aims to test a connection to a particular host NOT test if there is a connection to a network of any sort.

P.P.S. The Above works on Ubuntu 12.04 The /sys may not exist on some other distros. See below:

Modern Linux distributions include a /sys directory as a virtual filesystem (sysfs, comparable to /proc, which is a procfs), which stores and allows modification of the devices connected to the system, whereas many traditional UNIX and Unix-like operating systems use /sys as a symbolic link to the kernel source tree.[citation needed]

From Wikipedia https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard