Bash 循环 ping 成功

标签 bash shell unix while-loop ping

我在想这需要更改为一个 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/

相关文章:

linux - 两个子进程各创建3个子进程

linux - 以另一个用户身份执行命令并获取该进程的 PID

linux - |删除 : can't open | grep: can't open grep

regex - 我想在另一个字符串模式前面找到一些字符串,怎么办?

linux - Bash 脚本 - 嵌套 $(..) 命令 - 无法正常工作

c - 实现 DHCP 客户端

linux - 如何删除 sed 生成的换行符

mysql - 从其他脚本调用时,Linux 脚本和 MySql 操作不起作用

android - 无法在 adb shell getevent 上获得鼠标点击坐标

java - Notepad++ 当前目录