[Swan-dev] extract MAC address from "ip -o link sow dev eth0" - awk

Štěpán Brož stepan at izitra.cz
Fri Sep 20 10:47:47 UTC 2019


Hello Antony,

pá 20. 9. 2019 v 11:09 odesílatel Antony Antony <antony at phenome.org> napsal:

> programs/_updown.netkey/_updown.netkey.in
> -           if [ -r /sys/class/net/${iface}/address ]; then
> -               macaddr=$(cat /sys/class/net/${iface}/address)
> +           if ip -o link show dev ${iface}; then
> +               macaddr=$(ip -o link show dev ${iface} | awk '$2 != "${iface}:" {print $(NF-4)}')
>
> I am not sure "NF-4" is good idea. The fear is a hardcoded position of the
> MAC address may not very portable to older versions "ip". Will it be always
> at a -4 in "ip -o" output.  If not we need an awk magic line.
>
> Tuomo, would you write a better awk oneliner?

I'm not Tuomo, but are we limited to 'awk'? Can you go with e.g. sed?

(+ -- to match even for interfaces with longer MAC addresses, I've
seen it with some storage devices)
# sed -E 's/.*ether\ ([0-9a-f:]{17}+)\ brd.*$/\1/'

> Also this has two "ip -o" calls may be we can do in one?

I think you don't need to check for the "ip -o" return value, $macaddr
will be an empty string when the device does not exist.

Have fun,
Stepan


More information about the Swan-dev mailing list