需要一些额外的目光...
dns_lookup() {
ip_set
if [ `ip_ping ${ip_address}` -eq 0 ]
then
host=""
dig +short -x ${ip_address} | sed 's/\.$//g' | while read host
do
if [ -z "${host}" ]
then
host="unknown"
fi
echo "${ip_address},${host}"
done
fi
}
如果ip可ping并具有dns名称,我会得到所需的结果。如果ip可ping,但没有dns名称,我不会得到结果。
ip_set() {
ip_address="${a}.${b}.${c}.${d}"
}
ip_ping() {
timeout ${delay} ping -q -c 1 -i 1 -W 1 -w 4 $1 > /dev/null 2>&1 ; echo $?
}
答案 0 :(得分:0)
如果没有主机名,则不会得到结果,因为当没有要读取的行时,while read
循环永远不会运行。无论如何都应该使您的打印代码运行:
host=$(dig +short -x "${ip_address}" | sed 's/\.$//g')
if [ -z "${host}" ]
then
host="unknown"
fi
printf "${ip_address},%s\n" $host
另外,你的病情错了。您不应回显退出状态并将其作为文本进行比较。您应该让命令的退出状态为您的函数的退出状态:
ip_ping() {
timeout ${delay} ping -q -c 1 -i 1 -W 1 -w 4 $1 > /dev/null 2>&1
# functions implicitly 'return $?' if you don't specify anything else
}
现在您可以轻松检查您的功能:
if ip_ping "$ip_address"
then
echo "It worked"
else
echo "It failed.."
fi
答案 1 :(得分:0)
也许这就是你所需要的。如果您需要修改,请告诉我。
dns_lookup() {
ip_set
if [ `ip_ping ${ip_address}` -eq 0 ]
then
host=""
dig +short -x ${ip_address} | sed 's/\.$//g' | {
hashosts=false
while read host
do
if [ -n "${host}" ]
then
hashosts=true
echo "${ip_address},${host}"
fi
done
[ "${hashosts}" = false ] && echo "${ip_address},unknown"
}
fi
}
我还建议更改函数ip_ping但是that_other_guy已经完成了。