Skip to content

Instantly share code, notes, and snippets.

@ipleten
Last active July 18, 2019 22:51
Show Gist options
  • Save ipleten/72c10f599ebc03a07a02aa5a4349b32c to your computer and use it in GitHub Desktop.
Save ipleten/72c10f599ebc03a07a02aa5a4349b32c to your computer and use it in GitHub Desktop.
Bash retry function with delays.
#!/bin/bash
# helper funciton for retry NUM_TRIES times with SLEEP_TIME delays between each
function run_retry {
local SLEEP_TIME=$1
local NUM_TRIES=$2
shift 2
local CMD=$*
COUNT=0
echo "Running '$CMD'"
while [ $COUNT -lt $(($NUM_TRIES*$SLEEP_TIME)) ]; do
eval "$CMD"
EXIT_CODE=$?
if [[ $EXIT_CODE -eq 0 ]]; then
echo "Success!"
return 0
fi
echo "Retrying in ${SLEEP_TIME} sec [${COUNT}/$(($NUM_TRIES*$SLEEP_TIME)) sec]"
sleep $SLEEP_TIME
let COUNT=COUNT+SLEEP_TIME
done
echo "Reached retry limit. Exiting..."
return $EXIT_CODE
}
# run_retry 1 10 "echo $HOME | grep jbond"
# run_retry 1 10 curl google.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment