Skip to content

Instantly share code, notes, and snippets.

@dublx
Last active April 3, 2023 10:38
Show Gist options
  • Save dublx/e99ea94858c07d2ca6de to your computer and use it in GitHub Desktop.
Save dublx/e99ea94858c07d2ca6de to your computer and use it in GitHub Desktop.
Bash - retry command N times
#!/bin/bash
set -euo pipefail
function myFunction() {
myCommand
return $?
}
retry=0
maxRetries=5
retryInterval=15
until [ ${retry} -ge ${maxRetries} ]
do
myFunction && break
retry=$[${retry}+1]
echo "Retrying [${retry}/${maxRetries}] in ${retryInterval}(s) "
sleep ${retryInterval}
done
if [ ${retry} -ge ${maxRetries} ]; then
echo "Failed after ${maxRetries} attempts!"
exit 1
fi
@dublx
Copy link
Author

dublx commented Jan 5, 2015

Use this code to retry a Bash command/function N times with a retry interval.

@icefo
Copy link

icefo commented Jun 4, 2019

thank you ! that's exactly what I need. I wasn't sure how to do it without removing set -e

@dublx
Copy link
Author

dublx commented Jun 4, 2019

You're welcome!

@marcoczen
Copy link

marcoczen commented Jul 19, 2019

Thanks ...
What is the purpose of set -euo pipefail ?

@dublx
Copy link
Author

dublx commented Jul 20, 2019

@BD8806
Copy link

BD8806 commented Jan 4, 2021

this solved my problem too but how do we modify the retry logic to check for specific strings in the command output and then retry instead of just checking the exit code of the command.

@dublx
Copy link
Author

dublx commented Apr 27, 2021

Sorry @BD8806 I didnt see this last question - did you sort it out in the end?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment