继续重试纱线脚本,直到它通过 [英] Keep retrying yarn script until it passes

查看:39
本文介绍了继续重试纱线脚本,直到它通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 bash 新手,想知道是否有办法运行脚本 x 次直到它成功?我有以下脚本,但它自然会退出并且在成功之前不会重试.

I am new to bash and wondering if there is a way to run a script x amount of times until it succeeds? I have the following script, but it naturally bails out and doesn't retry until it succeeds.

yarn graphql
if [ $? -eq 0 ]
then
  echo "SUCCESS"
else
  echo "FAIL"
fi

我可以看到有一种方法可以连续循环,但是有没有办法限制它,比如每秒循环一次,持续 30 秒?

I can see there is a way to continuously loop, however is there a way to throttle this to say, loop every second, for 30 seconds?

while :
do
    command
done

推荐答案

我想你可以为此设计一个专用的 bash 函数,依赖于 sleep 命令.

I guess you could devise a dedicated bash function for this, relying on the sleep command.

例如,这段代码的灵感来自于 该代码由 Travis 提供,在 MIT 许可下分发:

E.g., this code is freely inspired from that code by Travis, distributed under the MIT license:

#!/usr/bin/env bash
ANSI_GREEN="\033[32;1m"
ANSI_RED="\033[31;1m"
ANSI_RESET="\033[0m"

usage() {
    cat >&2 <<EOF
Usage: retry_until WAIT MAX_TIMES COMMAND...

Examples:
  retry_until 1s 3 echo ok
  retry_until 1s 3 false
  retry_until 1s 0 false
  retry_until 30s 0 false
EOF
}

retry_until() {
    [ $# -lt 3 ] && { usage; return 2; }
    local wait_for="$1"  # e.g., "30s"
    local max_times="$2"  # e.g., "3" (or "0" to have no limit)
    shift 2
    local result=0
    local count=1
    local str_of=''
    [ "$max_times" -gt 0 ] && str_of=" of $max_times"
    while [ "$count" -le "$max_times" ] || [ "$max_times" -le 0 ]; do
        [ "$result" -ne 0 ] && {
            echo -e "\n${ANSI_RED}The command '$*' failed. Retrying, #$count$str_of.${ANSI_RESET}\n" >&2
        }
        "$@" && {
            echo -e "\n${ANSI_GREEN}The command '$*' succeeded on attempt #$count.${ANSI_RESET}\n" >&2
            result=0
            break
        } || result=$?
        count=$((count + 1))
        sleep "$wait_for"
    done
    [ "$max_times" -gt 0 ] && [ "$count" -gt "$max_times" ] && {
        echo -e "\n${ANSI_RED}The command '$*' failed $max_times times.${ANSI_RESET}\n" >&2
    }
    return "$result"
}

然后要完全回答您的问题,您可以运行:

Then to fully answer your question, you could run:

retry_until 1s 30 command

这篇关于继续重试纱线脚本,直到它通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆