Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using bash how can i get the network device name and ip address in one line?

Tags:

grep

bash

awk

I want to get the Network Interface device name (ens###) along with its associated IP address (###.###.###.###). I have solutions to get one or the other but I have not been able to find something that can output each pair (Name + IP) to a line.

Here is a command to get IP

ip address | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'

And here I can get the device name

ip address | grep -v lo | cut -d ' ' -f2 | tr ':' '\n' | awk NF

However I would like a way to get both which would output each set to their own line, something like this

ens32 10.0.0.100
ens33 10.1.0.100

EDIT:

Here is a sample output of ip address

[root@centos ~]# ip address
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:00:00:00:00:00 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.100/23 brd 10.0.1.255 scope global dynamic ens32
       valid_lft 83040sec preferred_lft 83040sec
    inet6 0000::000:0000:0000:0000/64 scope link
       valid_lft forever preferred_lft forever
3: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:00:00:00:00:00 brd ff:ff:ff:ff:ff:ff
    inet 10.1.0.100/24 brd 10.0.2.255 scope global dynamic ens33
       valid_lft 1277sec preferred_lft 1277sec
    inet6 0000::000:0000:0000:0000/64 scope link
       valid_lft forever preferred_lft forever

SOLUTIONS:

Both of these will give me the same desired output. Thanks for the help!

ip -o addr show scope global | awk '/^[0-9]:/{print $2, $4}' | cut -f1 -d '/'
ip -o addr show scope global | tr -s ' ' | tr '/' ' ' | cut -f 2,4 -d ' '
like image 961
bc81 Avatar asked Mar 04 '23 21:03

bc81


1 Answers

If you need a one-liner, try this (thanks to Dougie for the more refined ip command) :

ip -oneline -4 addr show scope global | tr -s ' ' | tr '/' ' ' | cut -f 2,4 -d ' '

-oneline forces output for each interface to a single line.

Then we cut out just the interface name and IP from the output, translating it a bit along the way (for cut to get rid of extra stuff).

like image 128
Vasan Avatar answered Apr 26 '23 07:04

Vasan