In BASH, Is there any way to find exactly the IP address for all interfaces? And remove all other information's?

1.6k views Asked by At

How can i get only IP and which interface IP it is? So that i can keep a record file such as realtime.ini

1 - test.sh

#!/bin/bash
ipstring ='inet (.*)'

for i in $(ip addr);
do
        echo $i #on found it write down to my realtime.ini as a list for future query
done

2 - realtime.ini

em1,192.168.1.2
lo,127.0.0.1
wlan0,<not found>

Follow up: Just for single ip: $ ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}' 192.168.1.2

2

There are 2 answers

0
Vala On BEST ANSWER

This is not terribly elegant, nor is bash, but you can do the following if you have both awk and sed:

ifconfig | awk 'BEGIN { FS = "\n"; RS = "" } { print $1 $2 }' | sed -e 's/ .*inet addr:/,/' -e 's/ .*//'

I wouldn't bet on this being hugely portable either, so maybe someone has a better answer.

0
Michał Šrajer On

if you install moreutils package, you can use handy ifdata command:

for INTF_PATH in /sys/class/net/* # list all interfaces
do
    INTF=$(basename $INTF_PATH) # interface name
    echo "$INTF,$(ifdata -pa $INTF)" # interface name and address
done

example output for 5 interfaces, while only eth0 and lo are up:

eth0,123.234.10.12
lo,127.0.0.1
vboxnet0,NON-IP
wlan0,NON-IP
wlan1,NON-IP