BASH
Implementing a Retry Mechanism for Unreliable Commands
Enhance Bash script reliability by adding a retry loop with exponential backoff for commands that might temporarily fail, such as network requests or resource access, improving resilience.
#!/bin/bash
MAX_RETRIES=5
INITIAL_BACKOFF_SECONDS=2
COMMAND_TO_RETRY="curl -s -f https://example.com/unreliable_service/status" # Example: A command that might fail
echo "Attempting to run command with retry logic..."
for ((i=1; i<=MAX_RETRIES; i++)); do
echo "Attempt $i/$MAX_RETRIES..."
# Execute the command and check its exit status
if eval "$COMMAND_TO_RETRY"; then
echo "Command succeeded on attempt $i!"
break
else
echo "Command failed on attempt $i."
if [[ $i -lt $MAX_RETRIES ]]; then
BACKOFF_SECONDS=$((INITIAL_BACKOFF_SECONDS * (2**(i-1)))) # Exponential backoff
echo "Retrying in $BACKOFF_SECONDS seconds..."
sleep "$BACKOFF_SECONDS"
else
echo "Maximum retries ($MAX_RETRIES) reached. Command failed permanently." >&2
exit 1
fi
fi
done
echo "Script continued after successful command execution (or exited if failed)."
How it works: This script implements a robust retry mechanism with exponential backoff for unreliable commands. It attempts to execute a specified command (`COMMAND_TO_RETRY`) up to `MAX_RETRIES` times. If the command fails, it waits for an exponentially increasing duration (`INITIAL_BACKOFF_SECONDS * 2^(attempt-1)`) before the next retry. If all retries fail, the script exits with an error; otherwise, it proceeds upon successful command execution. This pattern enhances script resilience against transient failures.