Last active
July 8, 2022 22:10
-
-
Save skchronicles/6743d4a86e6d16d05f68889717aee2c0 to your computer and use it in GitHub Desktop.
Retry a BASH command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
function err() { cat <<< "$@" 1>&2; } | |
function fatal() { cat <<< "$@" 1>&2; exit 1; } | |
function retry() { | |
# Tries to run a cmd 5 times before failing | |
# If a command is successful, it will break out of attempt loop | |
# Failed attempts are padding with the following exponential | |
# back-off strategy {4, 16, 64, 256, 1024} in seconds | |
# @INPUTS "$@"" = cmd to run | |
# @CALLS fatal() if command cannot be run in 5 attempts | |
local n=1 | |
local max=5 | |
local attempt=true # flag for while loop | |
while $attempt; do | |
# Attempt command and break out of attempt loop if successful | |
"$@" && attempt=false || { | |
# Try again up to 5 times | |
if [[ $n -le $max ]]; then | |
err "Command failed: $@" | |
delay=$(( 4**$n )) | |
err "Attempt: ${n}/${max}. Trying again in ${delay} seconds!\n" | |
sleep $delay; | |
((n++)) | |
else | |
fatal "Fatal: command failed after max retry attempts!" | |
fi | |
} | |
done | |
} | |
# Examples | |
retry ls /fake/directory/does/not/exist | |
retry ping 123.com |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
retry.py
Here is a python implementation of the same bash function above: