Retry a Bash command with timeout

前端 未结 5 640
情歌与酒
情歌与酒 2020-12-28 12:51

How to retry a bash command until its status is ok or until a timeout is reached?

My best shot (I\'m looking for something simpler):

NEXT_WAIT_TIME=0         


        
5条回答
  •  时光说笑
    2020-12-28 13:30

    retry fuction is from:

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

    #!/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
    

    if you want to retry an function in your script, you should do like this:

    # example usage:
    foo()
    {
       #whatever you want do.
    }
    
    declare -fxr foo
    retry 3 timeout 60 bash -ce 'foo'
    

提交回复
热议问题