edu*_*ike 18 unix bash shell ping while-loop
我认为这需要更改为while子句,此时它将等到所有10000次ping完成后,我需要它在ping成功时返回.程序"说"是在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
Run Code Online (Sandbox Code Playgroud)
好的,我没有权利回答我自己的问题,所以这是我在玩完之后的答案:
谢谢,是的,我不知道$?到现在.无论如何,现在我已经离开并做了这个.我喜欢你的不是永远不会,但在我的情况下,我不需要它停止,直到它完成.
#!/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"
Run Code Online (Sandbox Code Playgroud)
pax*_*blo 28
你可能不应该依赖命令的文本输出来决定这一点,特别是当ping
命令给你一个非常好的返回值时:
如果从指定的主机听到至少一个响应,ping实用程序将返回零退出状态; 如果传输成功但没有收到回复,则为2;
<sysexits.h>
如果发生错误,则返回另一个值.
换句话说,使用类似的东西:
((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
Run Code Online (Sandbox Code Playgroud)
Rob*_*vis 12
您不需要使用echo或grep.你可以这样做:
ping -oc 100000 8.8.8.8 > /dev/null && say "up" || say "down"
Run Code Online (Sandbox Code Playgroud)
这也可以通过超时完成:
# Ping until timeout or 1 successful packet
ping -w (timeout) -c 1
Run Code Online (Sandbox Code Playgroud)