How to get the MAC address of an active Ethernet connection in Bash Script?

Simple question:

How to get the MAC address of an active Ethernet connection in a bash script?

I currently have:

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

Which outputs the MAC address of eth0, but if eth1 is active, I want this instead.

Can I pre-execute ifconfig | grep inet ifconfig | grep inet , but that will not tell me which interface is active, only that one is active. I need to capture the line above it to tell me which one is the active connection.

Any help would be greatly appreciated.

Thanks!

+4
source share
2 answers

Found answer:

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

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

+2
source

you could do something like this

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

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

 route | awk '/default/ { print $NF }' | xargs -I {} ifconfig {} | awk '/HWaddr/ { print $5 }' 
+1
source

Source: https://habr.com/ru/post/1307606/


All Articles