继续重试 yarn script 直到它通过

Keep retrying yarn script until it passes

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

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

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

while :
do
    command
done

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

例如,此代码的灵感来自 that code by Travis, distributed under the MIT license:

#!/usr/bin/env bash
ANSI_GREEN="3[32;1m"
ANSI_RED="3[31;1m"
ANSI_RESET="3[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=""  # e.g., "30s"
    local max_times=""  # 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"
}

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

retry_until 1s 30 command