如何根据长期运行命令结果退出或重试
我正在尝试监视long_running_command
函数的输出(如果输出包含result ='good''
,然后print wow wow < /代码>并返回。但是,直到
long_running_command
没有返回result ='good'
继续尝试,直到达到max_try
。 到目前为止一切都很好。但是,如果命令已经返回result ='失败'
,则没有重试的点,我如何出错(打印nay
)不重试?
以下是示例程序(最小工作问题声明):
#!/bin/bash
MAX_TRY=5
#Simulating a fake long running command that may return good or failed randomly with a small delay
long_running_command()
{
wait_time=$(shuf -i 1-5 -n 1)
sleep "$wait_time"
if [ "$path" -eq 1 ];then
echo "result='good'"
elif [ "$path" -eq 0 ];then
echo "result='failed'"
else
echo "This path should never hit"
fi
}
# Some external conditions cannot be controlled by me, faking it
#0 means fail
#1 means pass
path=$(shuf -i 0-1 -n 1)
check_result() {
while [ $MAX_TRY -le 10 ];do
if long_running_command |grep -qE 'result.*good' ;then
echo "$(date): WOW"
return 0
fi
echo "$(date): Retrying...so far the output does not have good in it or perhaps its failed already"
MAX_TRY=$((MAX_TRY + 1))
done
echo "$(date): NAY"
}
check_result
TLDR,如果命令返回失败或良好,我需要从重试循环中退出。稍后,根据结果打印`哇或否。
I am trying to monitor the output of long_running_command
function(can't make changes to this), If the output contains result='good'
then print WOW
and return. However, until the long_running_command
did not return result='good'
keep trying until MAX_TRY
is reached. So far its all good. However, if the command already returned result='failed'
then there is no point of retrying, how can I error out(print NAY
) without retrying ?
Below is sample program(Minimum working problem statement):
#!/bin/bash
MAX_TRY=5
#Simulating a fake long running command that may return good or failed randomly with a small delay
long_running_command()
{
wait_time=$(shuf -i 1-5 -n 1)
sleep "$wait_time"
if [ "$path" -eq 1 ];then
echo "result='good'"
elif [ "$path" -eq 0 ];then
echo "result='failed'"
else
echo "This path should never hit"
fi
}
# Some external conditions cannot be controlled by me, faking it
#0 means fail
#1 means pass
path=$(shuf -i 0-1 -n 1)
check_result() {
while [ $MAX_TRY -le 10 ];do
if long_running_command |grep -qE 'result.*good' ;then
echo "$(date): WOW"
return 0
fi
echo "$(date): Retrying...so far the output does not have good in it or perhaps its failed already"
MAX_TRY=$((MAX_TRY + 1))
done
echo "$(date): NAY"
}
check_result
TLDR, I need to exit from the retry loop if the command has returned failed or good. Later, print `WOW or NAY based on the results.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将输出保存在变量中。然后,您可以测试它是否包含
result ='好'
或result ='失败'
。如果这两个,你都会重试。Save the output in a variable. Then you can test whether it contains
result='good'
orresult='failed'
. If neither, you retry.