Skip to content

Instantly share code, notes, and snippets.

@bboykov
Created March 27, 2020 07:52
Show Gist options
  • Save bboykov/e2963ce47c546dab80eea7d659f96a6b to your computer and use it in GitHub Desktop.
Save bboykov/e2963ce47c546dab80eea7d659f96a6b to your computer and use it in GitHub Desktop.
Retry or timeout bash function
#!/usr/bin/env bash
# Strict Mode - http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail
IFS=$'\n\t'
retry_command_or_timeout() {
local retry_command=${1}
local max_retries=${2}
local sleep_seconds=5
local retry_counter=0
echo "Retring: $retry_command"
until eval "$retry_command" >/dev/null 2>&1 || [ "$retry_counter" -eq "$max_retries" ]; do
echo "Waiting for $sleep_seconds seconds ..."
sleep "$sleep_seconds"
sleep_seconds=$((sleep_seconds * 2))
retry_counter=$((retry_counter + 1))
done
if [ "$max_retries" -eq "$retry_counter" ]; then
echo "Timeout reached."
exit 1
else
echo "Command completed successfuly."
fi
}
retry_command_or_timeout "ping -c 3 google.com" 3
retry_command_or_timeout "ping -c 3 test.com|grep something" 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment