Skip to content

Instantly share code, notes, and snippets.

@tombruijn
Last active January 16, 2024 16:14
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tombruijn/0cde5de10e86d91717ed855623929b05 to your computer and use it in GitHub Desktop.
Save tombruijn/0cde5de10e86d91717ed855623929b05 to your computer and use it in GitHub Desktop.
Retry until fail script

Until fail

Retry a command until it fails.

Debugging brittle specs is annoying and time consuming work. Let's automate finding those brittle specs by retrying them until they fail.

Accompanying blog post.

Usage

$ until-fail true
# Will repeat forever

$ until-fail false
# Fails at the first iteration and break out of the retry loop

$ until-fail ruby -e "(rand(0..1) == 1) ? (puts 'failed'; exit(1)) : (puts 'success')"
# Fails randomly and breaks out of the retry loop when it fails

Installation

  • Open a directory that's in your local $PATH. (See the list with echo $PATH in your terminal.)
  • Download the until-fail file from the gist. (Click the "Raw" button on the until-fail file.
  • Create a until-fail file in the open directory and paste in the until-fail file contents.
  • Make the file executable with chmod +x until-fail.
  • Now call the excutable with a command.
#!/bin/bash
# Retry a command until it fails
#
# Usage:
#
# $ until-fail true
# # Will repeat forever
#
# $ until-fail false
# # Fails at the first iteration and breaks out of the retry loop
#
# $ until-fail ruby -e "rand(0..1) == 1 ? (puts 'failed'; exit(1)) : (puts 'success')"
# # Fails randomly and breaks out of the retry loop when it fails
if [[ -z "$*" ]]; then
echo "ERROR: No command given to retry"
exit 1 # Error status
fi
i=0
while true; do
i=$((i + 1))
echo "================================================================================"
echo "Retry #$i: $*"
echo
# Run command and exit only if it fails
if ! "$@"; then
echo
echo "ERROR: Failure on retry #$i"
exit 1 # Exit loop with error status
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment