【问题标题】:Keep retrying yarn script until it passes继续重试纱线脚本,直到它通过
【发布时间】:2021-08-04 12:28:04
【问题描述】:

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

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

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

while :
do
    command
done

【问题讨论】:

  • while ! yarn graphql; do command; done?

标签: bash npm yarnpkg


【解决方案1】:

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

例如,这段代码的灵感来自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"
}

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

retry_until 1s 30 command

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 1970-01-01
    • 2015-05-28
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2012-12-03
    相关资源
    最近更新 更多