Best way to extract MAC address from ifconfig'

2019-01-21 04:28发布

What is the best way to extract the MAC address from ifconfig's output?

Sample output:

bash-3.00# ifconfig eth0        
eth0      Link encap:Ethernet  HWaddr 1F:2E:19:10:3B:52    
          inet addr:127.0.0.66  Bcast:127.255.255.255  Mask:255.0.0.0    
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          ....
          ....

Should I use cut, AWK or anything else, and what are the merits and demerits of one method over the other.

17条回答
孤傲高冷的网名
2楼-- · 2019-01-21 05:19

You can do a cat under /sys/class/

cat /sys/class/net/*/address

Specifically for eth0

cat /sys/class/net/eth0/address
查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-21 05:19
ifconfig | grep -i hwaddr | cut -d ' ' -f11
查看更多
甜甜的少女心
4楼-- · 2019-01-21 05:21

Since the OP's example refers to Bash, here's a way to extract fields such as HWaddr without the use of additional tools:

x=$(ifconfig eth0) && x=${x#*HWaddr } && echo ${x%% *}

In the 1st step this assigns the ouput of ifconfig to x. The 2nd step removes everything before "HWaddr ". In the final step everything after " " (the space behind the MAC) is removed.

Reference: http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion

查看更多
smile是对你的礼貌
5楼-- · 2019-01-21 05:21

Use:

ifconfig eth0 | grep HWaddr

or

ifconfig eth0 |grep HWaddr

This will pull just the MAC address and nothing else.

You can change your MAC address to whatever you want:

ifconfig eth0 down,
ifconfig eth0 hw ether (new MAC address),
ifconfig eth0 up
查看更多
Lonely孤独者°
6楼-- · 2019-01-21 05:24

Nice and quick one:

ifconfig eth0 | grep HWaddr | cut -d ' ' -f 11
查看更多
登录 后发表回答