Bash循环ping成功 [英] Bash loop ping successful
问题描述
我认为这需要更改为while子句,此刻它会等到所有10000个ping操作完成,当ping成功时,我需要它返回.程序"say"位于OSX上,它可以使计算机讲话.
I'm thinking that this needs to be changed to a while clause, at the moment it'll wait till all 10000 pings are done, I need it to return when the ping is successful. The program "say" is on OSX it makes the computer speak.
#!/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
好吧,我无权回答自己的问题,所以这是我玩耍后的答案:
OK I don't have rights to answer my own question so here's my answer for it after playing around:
谢谢,是的,我不知道$?到目前为止.无论如何,现在我走了,做了这个.我希望您的记忆不会永远消失,但在我的情况下,我并不需要它停止直到完成.
Thanks, yeah I didn't know about $? until now. Anyway now I've gone and made this. I like that yours doesn't go forever but in my situation I didn't need it to stop until it's finished.
#!/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实用程序将返回退出状态零.如果传输成功但未收到响应,则状态为"2";或
<sysexits.h>
中的另一个值(如果发生错误).
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.
换句话说,使用类似的东西:
In other words, use something like:
((count = 100)) # 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 to exit loop.
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成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!