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 am currently writing a bash script (for Nagios), and I would like to be able to detect if specific network cards are up or not.

My best guess is to do something like this:

ifconfig eth0 | grep UP | wc -l

or:

 ethtool eth0 | grep "Link detected: yes" | wc -l

Are either/both of those reliable ways of testing if the network card is up, or is there a better option? Perhaps there is a flag on ethtool which will do precisely what I want?

share|improve this question

4 Answers 4

up vote 1 down vote accepted

I think this is perhaps the best way to do it. You may want to do some more specific processing on the card, such as the grep you suggested with "Link detected: yes". make sure you escape special characters such as the colon, to make sure it is properly found. Also You can grep on its IP address segment, such as "192.168.25." for a class-C internal IP address. This would be based on your internal networking, whatever it is. But I think this is definitely the best way to do this.

There may also be some ways to actually detect a change, and trigger some event.

share|improve this answer
2  
Networks no longer use classes and colons don't need to be escaped –  Dennis Williamson Sep 17 '10 at 12:33
    
where you wrote "for a class C internal ip address" As they don't use classes anymore, that should read for a /24 internal ip address. –  barlop May 25 at 1:34

The show command from iproute-3.14.0-2 has this option:

up - only display running interfaces.

So if you run ip link show eth0 up and the interface is down, the output will be empty.

To check it, see question "test if a command returns a string or nothing in bash" from Stack Overflow. Basically something like this should do the trick:

test -n "`ip link show eth0 up`"

It exits with a status of 0 if the eth0 is up.

share|improve this answer

I think link detected… is not enough. You should also grep for the inet addr because even if a link could detect from the switch, the NIC may not has a valid IP address.

share|improve this answer

Check if interface is up:

ip link show eth0 | grep -qs "[<,]UP[,>]"

Check if it has any IPv4 addresses assigned:

ip -4 addr show eth0 | grep -Eqs "^\s"

In general, grep | wc -l should be replaced with grep -c if you want the match count.

Or grep -qs if you only want "match/no match" based on exit code: if stuff | grep -qs stuff; then ... fi

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.