4

Simple Question:

How do I grab the MAC address of the active Ethernet connection in a bash script?

I currently have:

set - `/sbin/ifconfig eth0 | head -1`
MAC=$5

Which outputs the MAC address of the eth0, but if it's eth1 that's active, I want that instead.

Could I beforehand execute ifconfig | grep inet but that wouldn't tell me which interface is active, just that one is active. I need to grab the line above it to tell me which one is the active connection.

Any help would be much appreciated.

Thank you!

1
  • 1
    What do you mean by "active interface"? Up? Carrying traffic? Associated with a default route?
    – rakslice
    May 5, 2011 at 4:54

2 Answers 2

2

Found the answer:

set - `ifconfig | grep -B 1 inet | head -1`
MAC=$5

I grep'd the inet string and returned the line before. Then use head to grab the first line.

1
  • This will not give you the MAC of the "active interface"
    – kSiR
    Apr 27, 2010 at 3:26
1

you could do something like this

ifconfig | awk '/eth/ { print $5 }'

also an option... depending on user may need to specify /sbin/ifconfig in the xargs

route | awk '/default/ { print $NF }' | xargs -I {} ifconfig {} | awk '/HWaddr/ { print $5 }'
2
  • This will list the MAC address of ALL eth interfaces, where as I only wanted to grab the MAC address of the active eth interface. Apr 22, 2010 at 1:33
  • Did the second one do the desired action?
    – kSiR
    Apr 26, 2010 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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