Skip to content

Instantly share code, notes, and snippets.

@dbowling
Created October 4, 2024 16:14
Show Gist options
  • Select an option

  • Save dbowling/49e07c6710783f19b56f70df461f6c1c to your computer and use it in GitHub Desktop.

Select an option

Save dbowling/49e07c6710783f19b56f70df461f6c1c to your computer and use it in GitHub Desktop.
Run 'Til Good
#!/bin/bash
# rtg ("Run 'Til Good")
#
# Usage: ./rtg [SLEEP_SECONDS] COMMAND
#
# Runs the specified COMMAND in a loop until it successfully exits
# (i.e., returns exit code 0). Waits SLEEP_SECONDS between attempts to
# run the COMMAND. If SLEEP_SECONDS is not provided, defaults to 60 seconds.
function usage {
echo "Usage: $0 [SLEEP_SECONDS] COMMAND"
echo ""
echo "Runs the specified COMMAND in a loop until it successfully exits"
echo "(i.e., returns exit code 0). Waits SLEEP_SECONDS between attempts to"
echo "run the COMMAND. If SLEEP_SECONDS is not provided, defaults to 60 seconds."
exit 1
}
function timestamp {
date +"%F %T"
}
SLEEP_SECONDS=60
# Check if the first argument is a number (sleep time)
if [[ "$1" =~ ^[0-9]+$ ]]; then
SLEEP_SECONDS="$1"
shift
# Ensure SLEEP_SECONDS is greater than zero
if [ "$SLEEP_SECONDS" -le 0 ]; then
echo "Error: SLEEP_SECONDS must be a positive integer."
usage
fi
fi
# Check if command is provided
if [ "$#" -eq 0 ]; then
echo "Error: No command provided."
usage
fi
while true; do
echo "[$(timestamp)] Command: $@"
"$@" && break
echo "[$(timestamp)] Waiting $SLEEP_SECONDS seconds to retry"
sleep "$SLEEP_SECONDS"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment