2

I use this command to get the name of my network interfaces and their mac address

ip -o link | awk '$2 != "lo:" {print $2, $(NF-2)}' | sed 's_: _ _'

out:

enp2s0 XX:XX:XX:XX:XX:XX
wlp1s0 YY:YY:YY:YY:YY

and this one to get the IP:

ip addr show $lan | grep 'inet ' | cut -f2 | awk '{ print $2}'

out:

127.0.0.1/8
192.168.1.23/24

or this one:

ifconfig | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'

or another:

ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1

out:

192.168.1.23

What command can I use to know (the order is not relevant):

interface name | IPv4 address | MAC address

example:

enp2s0 192.168.1.23 XX:XX:XX:XX:XX:XX

in a single line, but only from active interfaces (except lo) (for ubuntu 20.04)?

I have tried this solution but it did not work for me

acgbox
  • 891
  • 4
  • 11
  • 32

1 Answers1

3

In bash this works:

paste <(ip -o -br link) <(ip -o -br addr) | awk '$2=="UP" {print $1,$7,$3}'

but it relies on the ip output being in the same order for link and addr. To be sure, you could use join with sort instead:

join <(ip -o -br link | sort) <(ip -o -br addr | sort) | awk '$2=="UP" {print $1,$6,$3}'

In sh command substitution isn't available, so it couldn't be quite as concise as this.

zwets
  • 271
  • 1
  • 5
  • great, but almost. your command output comes out with ipv6 instead of ipv4. i think {print $1,$6,$3} (exclude net /24 please) – acgbox Jul 23 '21 at 22:18
  • Oww, there you go. On _my machine_ it gives the IPv4 address. Fair enough, `ip` doesn't claim to produce machine-parsable output, so we shouldn't be trying. Its json output (`-j`) should be better - but then it requires e.g. `jq` on the system. – zwets Jul 23 '21 at 22:39
  • it's weird for me. the first 'paste' command works fine, and the second I must change {print $1,$7,$3} to {print $1,$6,$3}. Ubuntu 20.04 – acgbox Jul 23 '21 at 23:00
  • is there a way to exclude netmask /24? – acgbox Jul 23 '21 at 23:03
  • It's not weird, it actually needs to be $6 in the second (I have corrected this), because `join` merges the join columns so there is one less. Yes, there are uncountable ways to get rid of the `/24`. Awk has `gsub`, or you could pipe everything through `sed -Ee 's./[0-9]+..'`. But the issue remains that you can't rely on `ip` output having any specific order or number of columns. – zwets Jul 23 '21 at 23:20
  • great works, thanks – acgbox Jul 23 '21 at 23:31
  • I wonder if `-o` actually does anything when `-br` is used. Btw there's `-4`. – Tom Yan Jul 24 '21 at 04:56
  • Someone knows how to escape the commands to be able to put it in an alias in bashrc? – elysch Jul 08 '23 at 16:44