如何在不正确的情况下运行函数10次并退出脚本

时间:2019-11-01 11:36:37

标签: bash

我有一个名为ping_test的函数,用于测试计算机是否响应ping:

function ping_test() { 
    ping xxx.xxx.xxx.xxx
    if [[ "$?" == "0" ]]; then
        echo "Machine is online"
        return 0         
    else    
        echo "Machine is offline"
        return 1
    fi  

}

other_function1
other_function2
while ! ping_test; do
ping_test
done
other_function3
other_function4
exit 0

在ping失败10次后如何退出脚本(不执行功能other_function3other_function4)?

2 个答案:

答案 0 :(得分:1)

尝试10次,如果成功则中断。

other_function1
other_function2

for ((i=0; i<10; i++)); do
    test && break
done || {
    echo "Pings failed"
    exit 1
}

other_function3
other_function4

for循环本身的退出状态将告诉您循环是自然结束(非零)还是由于成功测试后的break(零)而结束。

答案 1 :(得分:0)

我的ping(macOS)具有内置功能来支持您的用例:

ping -c 10 -o xxx.xxx.xxx.xxx

-c count用于

  

发送(和接收) count ECHO_RESPONSE数据包后停止

-o

  

收到一个应答包后成功退出。

这意味着您的代码可能如下所示:

pingtest() {
    if ping -c 10 -o xxx.xxx.xxx.xxx; then
        echo "Machine is online"
    else
        echo "Machine is offline"
        exit 1
    fi
}

other_function1
other_function2
pingtest
other_function3
other_function4

,整个重试机制由ping本身处理。

请注意,test并不是函数的最佳名称:它通常已经是内置的shell,并且是$PATH中二进制文件的名称。

相关问题