如何使用 bash 找出您的 IP 地址

How to find out your IP addresses using bash

我有一个有多个 IP 地址的服务器。我想在 bash 中计算出它们的确切值。我正在寻找类似的东西:

a=returnIpAddressStartingWith 10.60.12
b=returnIpAddressStartingWith 10.60.13

所以下面的returns:

> echo $a
10.60.12.23

在 linux 上有合理的方法吗?

您可以使用这样的函数进行搜索:

findip() {
   ip -4 addr | awk -v ip="" -F '[/[:blank:]]+' ' == "inet" && index(, ip){print }'
}

并通过以下方式找到 IP:

a=$(findip '10.60.12')

使用 grep/awk/cut 将其从 'ip addr show' 列表中解析出来,然后可选地,如果您需要将其作为数组访问,请将您的列表复制到 Bash 数组中:

# Create a string that is the list of all variables
IPSTR=`ip addr show | fgrep 'inet ' | fgrep -v '127.0.0.1' | awk '{ print  }' | cut -d '/' -f 1`
I=0
for IP in $IPSTR ; do
    IPARY[$I]=$IP
    I=$(($I+1))
done
echo "First IP in array is ${IPARY[0]}"
echo "Number of IP addresses in array is ${#IPARY[*]}"