What is the best way to extract the MAC address from ifconfig
\'s output?
Sample output:
bash-3.00# ifconfig eth0
eth0 Link
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
Nice and quick one:
ifconfig eth0 | grep HWaddr | cut -d ' ' -f 11
ifconfig en0 | grep ether - for wired mac address
ifconfig en1 | grep ether - for wireless mac address
Not sure whether there really are any advantages, but you can simply use awk:
ifconfig eth0 | awk '/HWaddr/ {print $5}'
Output of ifconfig:
$ifconfig
eth0 Link encap:Ethernet HWaddr 00:1b:fc:72:84:12
inet addr:172.16.1.13 Bcast:172.16.1.255 Mask:255.255.255.0
inet6 addr: fe80::21b:fcff:fe72:8412/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:638661 errors:0 dropped:20 overruns:0 frame:0
TX packets:93858 errors:0 dropped:0 overruns:0 carrier:2
collisions:0 txqueuelen:1000
RX bytes:101655955 (101.6 MB) TX bytes:42802760 (42.8 MB)
Memory:dffc0000-e0000000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:3796 errors:0 dropped:0 overruns:0 frame:0
TX packets:3796 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:517624 (517.6 KB) TX bytes:517624 (517.6 KB)
The best way to extract MAC address is:
ifconfig | sed '1,1!d' | sed 's/.*HWaddr //' | sed 's/\ .*//' | sed -e 's/:/-/g' > mac_address
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