Skip to main content

Bash script to retry a command (up to 3 times) if it fails.

#!/usr/bin/env bash

#
# Retries a command (up to 3 times) if it fails.
#
# This is based on travis_retry.bash
# https://github.com/travis-ci/travis-build/blob/master/lib/travis/build/bash/travis_retry.bash.
#
# Source:
# https://github.com/certbot/certbot/blob/master/tools/retry.sh
#
# Examples:
#
# Example command that executes without error(s):
#
#   $ retry.sh eval "curl https://example.com/api"
#   $ echo $?
#   0
#
# Example command that execute 3 times before returning with the error code:
#
#   $ retry.sh eval "curl http://127.0.0.1"
#   curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused
#   curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused
#   curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused
#   $ echo $?
#   7

set -e

result=0
count=1

while [[ "${count}" -le 3 ]]; do
    result=0
    "${@}" || result="${?}"
    if [[ $result -eq 0 ]]; then break; fi
    count="$((count + 1))"
    sleep 1
done

exit "${result}"