-
-
Notifications
You must be signed in to change notification settings - Fork 148
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a helper script to retry failed commands
- Loading branch information
Showing
1 changed file
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
#!/bin/sh | ||
|
||
set -e | ||
|
||
# SPDX-License-Identifier: GPL-2.0-or-later | ||
# | ||
# Copyright (C) 2022-2022 kcgen <kcgen@users.noreply.github.com> | ||
|
||
usage() | ||
{ | ||
printf "%s\n" "\ | ||
Usage: ATTEMPTS COMMAND [[ARG1] ARG2 ...] | ||
Where: | ||
ATTEMPTS : Retry the COMMAND up to this many times. | ||
COMMAND : The executable or command to run. | ||
ARG(s) : One or more arguments for the COMMAND. | ||
Note: Place COMMAND or ARG(s) inside single or double | ||
quotes if they contain spaces. | ||
" | ||
} | ||
|
||
# Setup the error handler | ||
error_code=1 | ||
fail() { | ||
if [ "$error_code" -ne 0 ]; then | ||
echo "$1" >&2 | ||
fi | ||
exit "$error_code" | ||
} | ||
|
||
# Check number of arguments | ||
if [ "$#" -lt 2 ]; then | ||
usage | ||
fail "Please provide both the number of ATTEMPTS and COMMAND to run." | ||
fi | ||
|
||
# Setup our current and total number of attempts | ||
attempt=1 | ||
attempts="$1" | ||
shift | ||
case "$attempts" in | ||
''|*[!0-9]*) usage; fail "$attempts is invalid, please provide a number 1 or greater" ;; | ||
esac | ||
if [ "$attempts" -lt 1 ]; then | ||
usage | ||
fail "$attempts cannot be a negative number, please provide a number 1 or greater" | ||
fi | ||
|
||
while true; do | ||
# reset the error code | ||
error_code=0 | ||
|
||
# Launch and capture the error code on failure | ||
$* || error_code=$? | ||
|
||
# Quit if it passed | ||
if [ "$error_code" -eq 0 ]; then | ||
break | ||
fi | ||
|
||
# Inform the user | ||
echo -n "\"$*\" quit with error-code $error_code on attempt $attempt of $attempts, " >&2 | ||
|
||
# Maybe loop again or bail out | ||
if [ "$attempt" -lt "$attempts" ]; then | ||
attempt=$((attempt+1)) | ||
sleep 1 | ||
echo "retrying ...\n" >&2 | ||
else | ||
fail "quitting.\n" | ||
fi | ||
done |