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

北城余情 提交于 2019-12-13 17:34:30

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/7805952/in-bash-is-there-any-way-to-find-exactly-the-ip-address-for-all-interfaces-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!