In BASH, Is there any way to find exactly the IP a

2019-08-14 19:23发布

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条回答
爷、活的狠高调
2楼-- · 2019-08-14 19:56

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
查看更多
够拽才男人
3楼-- · 2019-08-14 20:11

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.

查看更多
登录 后发表回答