在 shell 中重试

参考 1

注意代码是 GPL 的

#!/bin/bash
 
# Retries a command on failure.
# $1 - the max number of attempts
# $2... - the command to run
retry() {
    local -r -i max_attempts="$1"; shift
    local -r cmd="$@"
    local -i attempt_num=1
 
    until $cmd
    do
        if (( attempt_num == max_attempts ))
        then
            echo "Attempt $attempt_num failed and there are no more attempts left!"
            return 1
        else
            echo "Attempt $attempt_num failed! Trying again in $attempt_num seconds..."
            sleep $(( attempt_num++ ))
        fi
    done
}
 
# example usage:
retry 5 ls -ltr foo

Footnotes

  1. http://fahdshariff.blogspot.com/2014/02/retrying-commands-in-shell-scripts.html

本页面最后修改于 2021-11-23,距今约 1327

Created By 三三好记性不如烂 Wiki - 人工大脑CC BY-SA or CC BY-NC-SA 4.0