我有一个名为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_function3
和other_function4
)?
答案 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
中二进制文件的名称。