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

Antony Antony antony at phenome.org
Fri Sep 20 19:45:16 UTC 2019


On Fri, Sep 20, 2019 at 12:47:47PM +0200, Štěpán Brož wrote:
> 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.

Hi Stepan,

Your suggestion looks interesting. Thanks. The script is already using sed.

Would you like to send this idea to me as a patch then I can just apply, 
otherwise I will add this on Monday.

-antony


More information about the Swan-dev mailing list