I am working on a script to get all the network interfaces and ip addresses in Linux.
I know how to use ip command to get the ip address.
$ ip add show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
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
2: ens192: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:50:56:81:68:27 brd ff:ff:ff:ff:ff:ff
inet 10.252.9.61/23 brd 10.252.9.255 scope global noprefixroute ens192
valid_lft forever preferred_lft forever
but how to show format the output like this: interface name: ip address?
please give some suggestions. Thanks.
like this?
[student@workstation ~]$ ip -br a | awk -F' ' '{print$1 ": " $3}'
lo: 127.0.0.1/8
eth0: 172.25.250.9/24
virbr0: 192.168.122.1/24
[student@workstation ~]$ ip -br a | awk -F' ' '{print$1 ": " $3}' | awk '{sub("/.*", "");print $0;}'
lo: 127.0.0.1
eth0: 172.25.250.9
virbr0: 192.168.122.1
Hello @linuxlearning !
Try this :
awk '{print $NF,":" $2}': This uses awk to print the last field (interface name) and the second field (IP address) of each line.
cut -d '/' -f 1: This uses cut to extract only the part before the slash (/) from the IP address (to remove the subnet mask information).
sed 's/:/ : /': This uses sed to add spaces around the colon (:) to format the output as "interface name : IP address".
Hi @linuxlearning,
It's the abbreviation of the 'brief' option. Some of the 'ip' command options have abbreviations like `ip -brief address` ==`ip -br a`.
like this?
[student@workstation ~]$ ip -br a | awk -F' ' '{print$1 ": " $3}'
lo: 127.0.0.1/8
eth0: 172.25.250.9/24
virbr0: 192.168.122.1/24
[student@workstation ~]$ ip -br a | awk -F' ' '{print$1 ": " $3}' | awk '{sub("/.*", "");print $0;}'
lo: 127.0.0.1
eth0: 172.25.250.9
virbr0: 192.168.122.1
@tnishiok Thanks a lot for the help. It is working as expected. But I couldn't understand -b -r means even I checked the man page.
I got another solution from this article. https://www.howtouselinux.com/post/check-ip-address-in-linux
ip -4 -o a | cut -d ' ' -f 2,7 | cut -d '/' -f 1
lo 127.0.0.1
ens192 10.252.9.61
It is also working.
Hi @linuxlearning,
It's the abbreviation of the 'brief' option. Some of the 'ip' command options have abbreviations like `ip -brief address` ==`ip -br a`.
Hello @linuxlearning !
Try this :
awk '{print $NF,":" $2}': This uses awk to print the last field (interface name) and the second field (IP address) of each line.
cut -d '/' -f 1: This uses cut to extract only the part before the slash (/) from the IP address (to remove the subnet mask information).
sed 's/:/ : /': This uses sed to add spaces around the colon (:) to format the output as "interface name : IP address".
Hello @linuxlearning
You can try
Red Hat
Learning Community
A collaborative learning environment, enabling open source skill development.