我在想这需要更改为一个 while 子句,目前它会等到所有 10000 次 ping 都完成,我需要它在 ping 成功时返回。 “say”程序在 OSX 上,它让计算机说话。
#!/bin/bash
echo begin ping
if ping -c 100000 8.8.8.8 | grep timeout;
then echo `say timeout`;
else echo `say the internet is back up`;
fi
好吧,我没有权利回答我自己的问题,所以这是我在玩弄之后的答案:
谢谢,是的,我不知道 $?到目前为止。不管怎样,现在我已经去做了。我喜欢你的不会永远消失,但在我的情况下,我不需要它停止直到它完成。
#!/bin/bash
intertube=0
echo "begin ping"
while [ $intertube -ne 1 ]; do
ping -c 3 google.com
if [ $? -eq 0 ]; then
echo "ping success";
say success
intertube=1;
else
echo "fail ping"
fi
done
echo "fin script"
最佳答案
您可能不应该依赖命令的文本输出来决定这一点,尤其是当 ping
命令 gives you a perfectly good return value :
The ping utility returns an exit status of zero if at least one response was heard from the specified host; a status of two if the transmission was successful but no responses were received; or another value from
<sysexits.h>
if an error occurred.
换句话说,使用类似的东西:
((count = 60)) # Maximum number to try.
while [[ $count -ne 0 ]] ; do
ping -c 1 8.8.8.8 # Try once.
rc=$?
if [[ $rc -eq 0 ]] ; then
((count = 1)) # If okay, flag loop exit.
else
sleep 1 # Minimise network storm.
fi
((count = count - 1)) # So we don't go forever.
done
if [[ $rc -eq 0 ]] ; then # Make final determination.
echo `say The internet is back up.`
else
echo `say Timeout.`
fi
关于Bash 循环 ping 成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6118948/