github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/tests/includes/retry.sh (about) 1 # Retry a command until it succeeds (returns exit code 0). The retry strategy 2 # is a simple: retry after a fixed delay. 3 # usage: retry <command> [max_retries] [delay] 4 # 5 # Arguments: 6 # - command (required): the name of the command to retry. Usually a Bash 7 # function. The function should 'return 1' instead of 'exit 1', as calling 8 # 'exit' will terminate the whole test. 9 # - max_retries (optional): the number of times to retry. Defaults to 5. 10 # - delay (optional): the amount of time to sleep after an attempt. Defaults 11 # to 5 seconds. 12 retry() { 13 local command=${1} 14 local max_retries=${2:-5} # default: 5 retries 15 local delay=${3:-5} # default delay: 5s 16 17 local attempt=1 18 while true; do 19 echo "$command: attempt $attempt" 20 $command && break # if the command succeeds, break the loop 21 22 if [[ $attempt -ge $max_retries ]]; then 23 echo "$command failed after $max_retries retries" 24 return 1 25 fi 26 27 attempt=$((attempt + 1)) 28 sleep $delay 29 done 30 }