Skip to content
Advertisement

Get MAC address using shell script

Currently all the solution mentioned for getting the MAC address always use eth0. But what if instead of eth0 my interfaces start with eth1. Also on OS X the interface names are different.
Also the interface eth0 may be present but is unused. i.e. not active, it doesn’t have an IP.

So is there a way I could get the MAC address for the first available interface that is Active.(i.e. it has an inet address, I even don’t want one having inet6).

For E.g

eth0      Link encap:Ethernet  HWaddr <some addr>
          inet6 addr: <some addr> Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:123
          RX packets:123 errors:123 dropped:123 overruns:123 frame:123
          TX packets:123 errors:123 dropped:123 overruns:123 carrier:123
          collisions:123 txqueuelen:123 
          RX bytes:123 (123 MB)  TX bytes:123 (123 KB)
          Interrupt:123 Memory:00000000-00000000

eth1      Link encap:Ethernet  HWaddr <some addr>
          inet addr:<some addr>  Bcast:<some addr>  Mask:<some addr>
          inet6 addr: <some addr> Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:123 Metric:123
          RX packets:123 errors:123 dropped:123 overruns:123 frame:123
          TX packets:123 errors:123 dropped:123 overruns:123 carrier:123
          collisions:123 txqueuelen:123 
          RX bytes:123 (123 MB)  TX bytes:123 (123 KB)
          Interrupt:123 Memory:00000000-00000000

NOTE : I have changed the values of the output.

So in this case I want the HWaddr for eth1 and not eth0. How do I find it ? Also it should work on all the Linux flavours.

Advertisement

Answer

Observe that the interface name and the MAC address are the first and last fields on a line with no leading whitespace.

If one of the indented lines contains inet addr: the latest interface name and MAC address should be printed.

ifconfig -a |
awk '/^[a-z]/ { iface=$1; mac=$NF; next }
    /inet addr:/ { print iface, mac }'

Note that multiple interfaces could meet your criteria. Then, the script will print multiple lines. (You can add ; exit just before the final closing brace if you always only want to print the first match.)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement