Best way to extract MAC address from ifconfig's output?

You can do a cat under /sys/class/

cat /sys/class/net/*/address

Specifically for eth0

cat /sys/class/net/eth0/address

I would use:

ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'

The -o will cause grep to only print the part of the line that matches the expression. [[:xdigit:]]{1,2} will match 1 or 2 hexidecimal digits (Solaris doesn't output leading zeros).


I like using /sbin/ip for these kind of tasks, because it is far easier to parse:

$ ip link show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 1000
    link/ether 00:0c:29:30:21:48 brd ff:ff:ff:ff:ff:ff

You can trivially get the mac address from this output with awk:

$ ip link show eth0 | awk '/ether/ {print $2}'
00:0c:29:30:21:48

If you want to put a little more effort in, and parse more data out, I recommend using the -online argument to the ip command, which will let you treat every line as a new device:

$ ip -o link 
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue \    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 1000\    link/ether 00:0c:29:30:21:48 brd ff:ff:ff:ff:ff:ff
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 1000\    link/ether 00:0c:29:30:21:52 brd ff:ff:ff:ff:ff:ff
4: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 100\    link/[65534] 
5: sit0: <NOARP> mtu 1480 qdisc noop \    link/sit 0.0.0.0 brd 0.0.0.0

Not sure whether there really are any advantages, but you can simply use awk:

ifconfig eth0 | awk '/HWaddr/ {print $5}'