Skip to content

Instantly share code, notes, and snippets.

@ngocdaothanh
Last active June 28, 2022 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngocdaothanh/3174038fabb1ba06031d295190ce1c33 to your computer and use it in GitHub Desktop.
Save ngocdaothanh/3174038fabb1ba06031d295190ce1c33 to your computer and use it in GitHub Desktop.
Retry failed command with random delay
# Autoretry failed command 10 times, with 1-60s random delay:
# https://unix.stackexchange.com/questions/82598
for i in $(seq 1 10); do [ $i -gt 1 ] && delay=$[$RANDOM % 60 + 1] && echo "Retry after ${delay}s" && sleep $delay; command "$1" && failed=0 && break || failed=$?; done; (exit $failed)
CMD=$1
# Autoretry failed command 10 times, with 10-60s random delay:
# https://unix.stackexchange.com/questions/82598
MAX_RUNS=10
MIN_DELAY=10
MAX_DELAY=60
for i in $(seq 1 $MAX_RUNS)
do
random_range=$(($MAX_DELAY - $MIN_DELAY))
delay=$((RANDOM % $random_range + $MIN_DELAY))
[ $i -gt 1 ] && echo "Command failed, will retry (run $i/$MAX_RUNS) after $delay seconds" && sleep $delay
echo "Running command: $@"
command "$@" && failed=0 && break || failed=$?
done
exit $failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment