我正在尝试创建一个脚本,该脚本仅在pinging没有响应时才会继续。
我遇到了两个主要问题。一个是它需要2个CTL-C命令来结束脚本,另一个问题是脚本永远不会结束,需要终止。
以下是我的尝试;
rc=0
until [ $rc -gt 0 ]
do
ping 69.69.69.69 > /dev/null 2>&1
rc=$?
done
## Here will be the rest of code to be executed我觉得上面的这个非常接近,因为它需要2个CTL-C命令并继续。这是我在SO上找到的一些东西,但根本就不能工作。
counter=0
while [ true ]
do
ping -c 1 69.69.69.69 > /dev/null 2>&1
if [ $? -ne 0 ] then
let "counter +=1"
else
let "counter = 0"
fi
if [ $counter -eq 10 ] then
echo "Here should be executed once pinging is down"
fi
done非常感谢您的帮助,谢谢。
发布于 2017-03-07 22:38:13
试试这个:
while ping -c 1 -W 20 "$host" >& /dev/null
do
echo "Host reachable"
sleep 10 # do not ping too often
done
echo "Host unreachable within 20 seconds"发布于 2017-03-07 22:41:33
这有几个问题:首先,if语句是错误的,使用以下格式
if [ $? -ne 0 ] then;或此其他格式
if [ $? -ne 0 ]
then其次,我怀疑您的ping命令没有超时
ping -c 1 -w 2 69.69.69.69 > /dev/null 2>&1可能会有帮助
第三,您的循环将继续递增计数器,即使在10之后。
while [ $counter -le 10 ]如果在x秒后ping超时而没有任何响应,您会对执行某项操作感到满意,那么可以将其全部压缩(在下面的示例中为10秒):
ping -c 1 -w 10 69.69.69.69 >/dev/null 2>&1 || echo "run if ping timedout without any response"https://stackoverflow.com/questions/42650751
复制相似问题