Skip to content

Instantly share code, notes, and snippets.

@BoyPlankton
Last active August 29, 2015 14:26
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 BoyPlankton/5897c0f79fcf71ec627a to your computer and use it in GitHub Desktop.
Save BoyPlankton/5897c0f79fcf71ec627a to your computer and use it in GitHub Desktop.
BASH function for automatically rerunning processes if they fail.
function retryIfError() {
dry=3 # Default number of tries
dtl=60 # Default number of seconds to wait
drc=0 # Default return code
cmd=$1 # Command to call
try=${2-$dry} # Number of times to try
ttl=${3-$dtl} # Number of seconds to wait before trying again
erc=${4-$drc} # Expected return code on success
MAILTO=someone@somewhere.com
for cx in $(seq ${try})
do
eval "${cmd}"
rc=$?
if [ ${rc} -eq ${erc} ]
then
break
else
if [ ${cx} -ne ${try} ]
then
mailx -s "RETRYING ${0##*/} - $(date +%Y%m%d)" ${MAILTO} << !
Command: ${cmd}
Return Code: ${rc}, Expected: ${erc}
We have attempted to execute the command ${cx} times. We will try a total of ${try} times. Next attempt will be in ${ttl} seconds.
Thanks!
!
sleep ${ttl}
else
mailx -s "RETRYING ${0##*/} - $(date +%Y%m%d)" ${MAILTO} << !
ERROR! Max Retries Exceeded!
Command: ${cmd}
Return Code: ${rc}, Expected: ${erc}
We have attempted to execute the command ${cx} times. There will be no further attempts.
Thanks!
!
exit ${rc}
fi
fi
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment