源码:
get_local_ips.sh
#!/bin/bash
get_ip_from_device_index()
{
index=$1
sed_cmd="sed -ne '/^$((index)):/,/^$((index+1)):/p'"
ip a|eval $sed_cmd|grep inet|awk '{ip=substr($2,1,index($2,"/")-1);print ip}'
}
get_index_from_device_name()
{
name=$1
sed_cmd="ip a|sed -ne '/^[0-9]:[ ]$name:/p'|cut -d: -f1"
eval $sed_cmd
}
usage()
{
cat<<-EOF
echo usage: $0 <--name NAME|--index INDEX>
--name: network device name(eg. wlan0,eth0 etc.).
--index: network device index(could get it from command 'ip address').
EOF
}
main()
{
case $1 in
--name)
device_name=$2
device_index=`get_index_from_device_name $device_name`
get_ip_from_device_index $device_index
;;
--index)
device_index=$2
get_ip_from_device_index $device_index
;;
*)
usage
;;
esac
}
main $@
注意:此脚本基于ip address命令的执行结果
使用举例:
比如,执行ip a命令后的结果如下:
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
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: enp0s25: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN group default qlen 1000
link/ether 3c:97:0e:2d:bd:41 brd ff:ff:ff:ff:ff:ff
3: wlp3s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether e0:06:e6:cc:ae:b3 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.112/24 brd 192.168.1.255 scope global dynamic noprefixroute wlp3s0
valid_lft 70129sec preferred_lft 70129sec
inet6 fe80::c8fa:8f6b:cdf8:f34b/64 scope link noprefixroute
valid_lft forever preferred_lft forever
4: virbr0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
link/ether 52:54:00:1b:42:84 brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
6: vnet1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master virbr0 state UNKNOWN group default qlen 1000
link/ether fe:54:00:59:58:85 brd ff:ff:ff:ff:ff:ff
inet6 fe80::fc54:ff:fe59:5885/64 scope link
valid_lft forever preferred_lft forever
这些以(数字:)开头的行中,数字称作索引,数字后面即为接口名称
通过索引获取接口ip
比如:
./get-local-ips.sh --index 3
执行结果:
192.168.1.112
fe80::c8fa:8f6b:cdf8:f34b
通过名称获取接口ip
比如:
./get-local-ips.sh --name wlp3s0
执行结果同上。
标签:index,00,shell,ip,lft,ff,device,网络接口 From: https://blog.51cto.com/u_3823536/6021204