#!/bin/bash
# Script source: https://stackoverflow.com/questions/7449772/how-to-retry-a-command-in-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 -i attempt_num=1
    local -i delay=10
    until "$@"
    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 $delay seconds..."
            sleep $delay
            $((attempt_num++))
            delay=$((delay * 2))
        fi
    done
}

retry "$@"
