我正在维护一个在 RHEL 5 上运行的 bash 脚本。给定一个域名,我想确保当前机器上有一个接口(interface)监听预期的 IP 地址。
# Check that the IP is bound to this host, to avoid running on the wrong machine.
IP=$(dig +short ${EXPECTED_SUBDOMAIN}.example.com | tail -n 1)
if ! $(/sbin/ifconfig 2>/dev/null | /bin/grep -q $IP) ; then
echo "IP for ${EXPECTED_SUBDOMAIN} ($IP) doesn't appear to be on this host"
exit 1
fi
当 IP 地址是彼此的子字符串时,这会中断。如果我预期的 IP 地址是 1.2.3.4
,如果机器的 IP 地址(甚至子网掩码!)为 11.2.3.4
或 ,它不会退出>1.2.3.40
.
我能看到的唯一解决方案是 grep "inet addr:${IP} "
但搜索其他文本似乎很脏。
是否有更可靠的方法来找出接口(interface)的 IP 地址(不会被子网掩码之类的东西弄糊涂)并进行比较?有没有更好的方法?
最佳答案
在你的 grep 中使用单词边界:
if ! $(/sbin/ifconfig 2>/dev/null | /bin/grep -qE "\<$IP\>" ; then
...
关于linux - 如何确定是否有任何接口(interface)正在监听给定的 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24432268/