Different functions for different purposes:
## (1) check if there is any interface UP
## loopback interface (lo) is excluded
_isInterfaceUp(){
ip link|grep -v '[0-9]: lo:' 2>/dev/null|grep -l '^[0-9].* UP ' >/dev/null 2>&1
}
## (2) check if there is a valid default gateway in the routing table
## note: routes via non-active interfaces are excluded
_isNetworkUp(){
ip route|grep '^default via ' 2>/dev/null|grep -lv 'linkdown' >/dev/null 2>&1
}
## (3) check if Internet is connected properly
_isInternetConnected(){
if ! ping -c 4 8.8.8.8 >/dev/null 2>&1; then
## ping might be firewalled, so check a webpage then
curl -Hfs www.google.com >/dev/null 2>&1 || return 1
fi
return 0
}
In real practices, I do not use the function (1), because it rarely useful simply to check if there is an interface UP. However I do use funtions (2) + (3):
- The function (2)
_isNetworkUp
is called periodically in a script just to show whether my computer is networked
- The function (3)
_isInternetConnected
is called in a script before doing something with internet, like sync computer time and check email. Because the function (3) costs more time and resources than function (2), so it is not suitable for periodically usage of short time interval. curl
is more costly than ping
; so ping
first, then curl
later.
(sorry if my English is lousy).
Examples:
## if Internet is connected, then sync time
## with world time server
if _isInternetConnected; then
sudo ntpdate pool.ntp.org
sudo hwclock --systohc --utc
fi
Explanations:
grep -l
: grep
stops immediate after 1st found.
grep -v
: grep
exclusively.
ping -c 4
: ping
only 4 times.