【发布时间】:2014-06-26 13:46:18
【问题描述】:
我正在维护一个在 RHEL 5 上运行的 bash 脚本。给定一个域名,我想确保当前机器上有一个接口监听预期的 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} ",但搜索其他文本似乎很脏。
是否有更可靠的方法来找出接口的 IP 地址(不会被子网掩码之类的东西弄糊涂)并进行比较?有更好的方法吗?
【问题讨论】:
-
id 说可以在 grep 模式中使用额外的文本,以确保您只匹配字符串中所需的区域。