Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How to get the network status (online/offline) and attribute it to a variable in shell script?

share|improve this question
up vote 2 down vote accepted

another one... for older NICs, the command mii-tool is awesome

share|improve this answer
+1 It's really interesting! – Tom Brito Mar 4 '11 at 12:44

If you use network manager for your network connection, you could query it via dbus somewhat like this:

dbus-send --type=method_call --print-reply --system --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" org.freedesktop.NetworkManager.state

(somewhat deprecated but still works, for newer interfaces you'd just query a different address)

If that returns a "3" you are "connected" as described in http://projects.gnome.org/NetworkManager/developers/spec.html#type-NM_STATE (but it says nothing about internet connectivity).

If you really wanna know whether you have internet connectivity, just ping a remote server like google.com and see if that worked or not.

share|improve this answer

I'm going to reccomend ip again:

status=$(ip -o link show eth0 | awk '{print $9}')

(The ninth column is the state of the interface)

share|improve this answer
Strange that it shows "UNKNOWN" when connected. It works, as it shows "DOWN" when disconnected, but is it correct to show "UNKNOWN" when connected? – Tom Brito Mar 3 '11 at 16:54
I get UNKNOWN on a Ubuntu 10.10 system, and `1000` on a CentOS 5.5 system. – Stefan Lasiewski Mar 3 '11 at 18:42

You say you simply want the online/offline status of an interface, and aren't concerned with speed or link-type.

Try ethtool, as root:

# ethtool eth0 |grep "Link detected"
  Link detected: yes
# ethtool eth1 |grep "Link detected"
  Link detected: no

ifconfig can also show you the online/offline status, and this command is usually available to any user on the system.

$ { /sbin/ifconfig eth0 | grep MTU: | grep -w UP >/dev/null 2>&1 ; }; echo $?
# This could return some false errors
$ { /sbin/ifconfig eth1 | grep MTU: | grep -w UP >/dev/null 2>&1 ; }; echo $?
share|improve this answer

Your Answer


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.