Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps