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

前端 未结 19 1871
面向向阳花
面向向阳花 2020-12-12 15:31

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

Sample output:

bash-3.00# ifconfig eth0        
eth0      Link          


        
19条回答
  •  误落风尘
    2020-12-12 16:02

    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

提交回复
热议问题