bash 重复运行一个 shell 命令直到它失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12967232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:51:02  来源:igfitidea点击:

Repeatedly run a shell command until it fails?

bash

提问by bradley.ayers

I've written a fuzzytest that fails unreliably. I've added some debug code, but now I want to run the test until it fails so I can gather the debug output.

我写了一个模糊测试,它不可靠地失败了。我添加了一些调试代码,但现在我想运行测试直到它失败,以便我可以收集调试输出。

I've setup the test so I can run it using:

我已经设置了测试,所以我可以使用以下方法运行它:

./runtest

My current solution is to write an untilfailscript:

我目前的解决方案是编写一个untilfail脚本:

#!/bin/bash
$@
while [ $? -eq 0 ]; do
    $@
done

Then use it:

然后使用它:

untilfail ./runtest

Is there a simpler solution?

有没有更简单的解决方案?

回答by nneonneo

whiletakes a command to execute, so you can use the simpler

while需要一个命令来执行,所以你可以使用更简单的

while ./runtest; do :; done

This will stop the loop when ./runtestreturns a nonzeroexit code (which is usually indicative of failure).

这将在./runtest返回非零退出代码(通常表示失败)时停止循环。

To further simplify your current solution though, you should just change your untilfail script to look like this:

不过,为了进一步简化您当前的解决方案,您应该将 untilfail 脚本更改为如下所示:

#!/bin/bash

while "$@"; do :; done

And then you can call it with whatever command you're already using:

然后你可以用你已经在使用的任何命令调用它:

untilfail ./runTest --and val1,val2 -o option1 "argument two"

回答by Judd Rogers

If you don't want to wrap a complex pipe line into a shell script or function then this works:

如果您不想将复杂的管道包装到 shell 脚本或函数中,则可以这样做:

while true; do 
  curl -s "https:..." | grep "HasErrors.:true"
  if [[ "$?" -ne 0 ]]; then 
    break
  fi
  sleep 120
done

The HTTP request in this case always returns 200 but also returns some JSON which has an attribute "HasErrors":true when there is an error.

在这种情况下,HTTP 请求总是返回 200,但也会在出现错误时返回一些具有属性“HasErrors”:true 的 JSON。

回答by Graham Leggett

Having had a similar problem in a system that had shell retry logic duplicated everywhere I made a dedicated tool to solve this called "retry":

在一个系统中遇到了类似的问题,该系统的 shell 重试逻辑随处重复,我制作了一个专用工具来解决这个问题,称为“重试”:

retry --until=fail ./runtest

A more complex example:

一个更复杂的例子:

retry --until=fail --message="test succeeded" --delay=1 ./runtest

Tool available from https://github.com/minfrin/retry.

可从https://github.com/minfrin/retry获得的工具。