From ed60d6666bf3f4d7506cda1c38757e16f70d0184 Mon Sep 17 00:00:00 2001 From: Nicolas MASSE Date: Fri, 7 Jan 2022 12:56:55 +0100 Subject: [PATCH] initial commit --- retries/retries.sh | 52 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100755 retries/retries.sh diff --git a/retries/retries.sh b/retries/retries.sh new file mode 100755 index 0000000..9f5043a --- /dev/null +++ b/retries/retries.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +function retry () { + local i=5 delay=1 + while [ $i -gt 0 ]; do + i="$((i-1))" + + # save shell flags to restore them later + bash_flags="$-" + + # execute the given command + set +e + "$@" + ret=$? + + # restore flags since we modified them above + if [[ "$bash_flags" == *e* ]]; then + set -e + fi + + if [ $ret -gt 0 ]; then + echo "$1 failed. Retrying in $delay seconds..." + sleep $delay + continue + else + return 0 + fi + done + + echo "Giving up..." + return 1 +} + +function fail () { + echo "$@" + exit 255 +} + +echo "Testcase: false" +retry false +[ $? -gt 0 ] || fail "assert failed" + +echo +echo "Testcase: true" +retry true +[ $? -eq 0 ] || fail "assert failed" + +echo +echo "Testcase: random" +retry /bin/sh -c 'echo random; [ $RANDOM -lt 6000 ]' + +