Sorting “ip addr” output by device name

I got this small industrial computer thing that’s supposed to become a linux router / packet filter. It has 8 network interfaces, some 1 gigahertz CPU and a gig of RAM. Fanless design, rack mountable, data sitting on a CF card. Nice platform you might say.

While looking at the front I noticed an interface numbering that popped the word “weird” into my head, but I didn’t pay much attention due to the still going thrill of unpacking new hardware. The 4 fast ethernet were numbered 1-4 but from right to left. The 4 gigabit ethernet interfaces were numbere I-IV, also from right to left.

After installing linux and playing around a little bit, I started configuring it for what it’s supposed to do. One of the first things I needed to find out was: Which eth device corresponds to which port on the outside? Turns out eth0 is not the leftmost, but also not the rightmost port. Instead it’s the second port from the left.

I knew that the naming of ethernet devices was something in udev and that it remembers the mac addresses in order to uniquely identify each NIC. So I edited /etc/udev/rules.d/*net.rules and made a configuration where eth0 is the leftmost, eth7 the rightmost port. That way it would be most intuitive I figured. After a reboot, I saw this:

ip a|egrep "^[0-9]+"
1: lo:  mtu 16436 qdisc noqueue state UNKNOWN
2: eth4:  mtu 1500 qdisc noop state DOWN qlen 1000
3: eth5:  mtu 1500 qdisc noop state DOWN qlen 1000
4: eth0:  mtu 1500 qdisc noop state DOWN qlen 1000
5: eth6:  mtu 1500 qdisc noop state DOWN qlen 1000
6: eth7:  mtu 1500 qdisc noop state DOWN qlen 1000
7: eth1:  mtu 1500 qdisc pfifo_fast state UP qlen 1000
8: eth2:  mtu 1500 qdisc pfifo_fast state UP qlen 1000
9: eth3:  mtu 1500 qdisc noop state DOWN qlen 1000

Erm, yeah, you’ve got to be kidding me. Counting for dummies: 4,5,0,6,7,1,2,3.

I spent an hour trying to find a way to tell “ip” to sort its output by device name and guess what I found: nuthin.

So, the reason for me to open this blog boils down to one line of code that, after this experience, I felt like sharing.

function ip() {
  if echo $*|egrep -q \
  "^(a|addr)([[:space:]]*$|[[:space:]]+(s|show)[[:space:]]*$)"; then
    for dev in $(/sbin/ip addr show | \
    awk 'BEGIN{FS=":";}{if ($1 ~/^[0-9]+/){ print $2; } }'|sort)
    do
      /sbin/ip addr show $dev
    done
  else
    /sbin/ip $*
  fi
}

hth

Advertisements

One response to “Sorting “ip addr” output by device name

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s