Skip to content

Instantly share code, notes, and snippets.

@dublx
Last active July 8, 2024 12:34
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 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?

@missinglink
Copy link

for i in {1..5}; do myFunction && break || sleep 15; done

@dublx
Copy link
Author

dublx commented Jul 8, 2024

for i in {1..5}; do myFunction && break || sleep 15; done

Perfect, thanks!

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