Skip to content

Instantly share code, notes, and snippets.

@yoshikakbudto
Last active April 10, 2021 17:45
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 yoshikakbudto/13280073427873b614cfa042e1679817 to your computer and use it in GitHub Desktop.
Save yoshikakbudto/13280073427873b614cfa042e1679817 to your computer and use it in GitHub Desktop.
bash function that progresive retries a command with support of "ok exit codes"
# $1 exit code
# $2 ok exit codes (comma separeted)
#
verify_exitcode(){
local j
for j in ${2//,/ };do
if [ $j -eq $1 ]; then
echo "[info] assume exit code $j as ok"
return 0
fi
done
return $1
}
# accepts:
# $1: retries count
# $2: seconds to wait between retries
# $3(optional): ok exit codes in the form of list separeted by commas. Ex: "0,1,2,3"
# $4: command
# $5,...: command arguments
#
# Control Variables
# RETRY_INCREMENT_SECS (default is 30) : increment each subsequent retry timeout by this number of seconds
#
retry(){
local retries retry_wait_secs ok_exitcodes cmd j
RETRY_INCREMENT_SECS="${RETRY_INCREMENT_SECS:-30}"
[ $# -lt 3 ] && {
echo "func retry() accepts at least 3 args: retries, sleep time, cmd"
exit 2
}
retries=$1 && shift
retry_wait_secs=$1 && shift
if [[ $1 =~ ^[0-9] ]];then
ok_exitcodes=$1 && shift
else
ok_exitcodes=0
fi
cmd="$1" && shift
printf "\n[info] going to try $retries times pausing for $retry_wait_secs seconds in between..."
for j in $(seq $retries); do
printf "\n[info] try $j...\n"
$cmd -- "$@"
verify_exitcode $? $ok_exitcodes
if [ $? -eq 0 ]; then
exit 0
elif [ $j -ne $retries ]; then
printf "\n[info] sleeping for ${retry_wait_secs} seconds before retry...\n\n"
sleep $retry_wait_secs
else
exit $?
fi
: $(( retry_wait_secs += RETRY_INCREMENT_SECS ))
done
}
retry 3 2 ls "not existing file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment