Skip to content

Instantly share code, notes, and snippets.

@duruyao
Last active October 18, 2022 07:04
Show Gist options
  • Save duruyao/b93b96b5c17dbee4ba4d1ad31c55c547 to your computer and use it in GitHub Desktop.
Save duruyao/b93b96b5c17dbee4ba4d1ad31c55c547 to your computer and use it in GitHub Desktop.
Retry running a command if fails.
#!/usr/bin/env bash
## date: 2022-01-19
## author: duruyao@gmail.com
## desc: retry running a command if fails
## usage: retry <COMMAND>
set -euo pipefail
command=("$@")
timeout="5s"
logfile="/tmp/retry/$(TZ=UTC-8 date "+%Y-%m-%d")/$(echo "${RANDOM}" | md5sum | head -c 20).log"
mkdir -p "$(dirname "${logfile}")"
printf "[%19s] Run '%s', see '%s' for more output\n" "$(TZ=UTC-8 date "+%Y-%m-%d %H:%M:%S")" "${command[*]}" "${logfile}"
while ! (bash -x -c "${command[@]+"${command[@]}"}" 1>>"${logfile}" 2>&1); do
sleep "${timeout}"
printf "[%19s] Run '%s', see '%s' for more output\n" "$(TZ=UTC-8 date "+%Y-%m-%d %H:%M:%S")" "${command[*]}" "${logfile}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment