How do you implement retry with exponential backoff as a function?
IntermediateConceptFunctions, exit codes, strict mode and traps
Answer
retry() { # retry ATTEMPTS DELAY cmd args...
local _max=$1 _delay=$2 _try=1 _rc
shift 2
until "$@"; do
_rc=$?
(( _try >= _max )) && return "$_rc"
echo "attempt $_try/$_max failed ($_rc), retry in ${_delay}s" >&2
sleep "$_delay"
_try=$((_try + 1)) _delay=$((_delay * 2))
done
}
retry 5 2 aws s3 cp "$archive" "s3://$bucket/$key"
Pass the command as separate arguments ("$@"), never as a string to eval. Add jitter (sleep $((_delay + RANDOM % 3))) when many hosts retry at once. Only retry idempotent operations.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner