As asked
Write a Bash function called retry that takes a command as its arguments and retries it up to 5 times with exponential backoff starting at 2 seconds, printing the attempt number each time and returning a non-zero exit code if all attempts fail.
Sample answer outline
The function should use a loop from 1 to MAX_ATTEMPTS, run the command with $@, check the exit code, sleep for 2^attempt seconds on failure using arithmetic expansion, and return 1 after all attempts. A strong answer handles quoting of arguments correctly and avoids swallowing the exit code.
Reference implementation (bash)
retry() {
local max_attempts=5
local attempt=1
local delay=2
until "$@"; do
if (( attempt == max_attempts )); then
echo "All $max_attempts attempts failed."
return 1
fi
echo "Attempt $attempt failed. Retrying in ${delay}s..."
sleep "$delay"
(( attempt++ ))
(( delay = delay * 2 ))
done
}Expect these follow-ups
- How would you add a jitter to the backoff to avoid thundering herd when many scripts retry at the same time?
- How would you make this function work correctly when the command contains pipes or redirections?