Skip to content

Instantly share code, notes, and snippets.

@csghone
Created July 20, 2018 04:23
Show Gist options
  • Select an option

  • Save csghone/018ea28767ebc9eaad9f4dc2e99b6f78 to your computer and use it in GitHub Desktop.

Select an option

Save csghone/018ea28767ebc9eaad9f4dc2e99b6f78 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Source this in your script to use these functions
function bash_check_int {
if [ "$1" -eq "$1" ] 2>/dev/null; then
return 0
fi
echo "$2 must be an integer"
return -1
}
function bash_retry_loop {
if [ $# -lt 3 ]; then
echo "Wrong arguments. bash_retry_loop <loop_count> <loop_delay> <command>"
return -1
fi
max=$1
delay=$2
bash_check_int $max "First arg (loop_count)"
if [ $? -ne 0 ]; then return -1; fi
bash_check_int $delay "Second arg (loop_delay)"
if [ $? -ne 0 ]; then return -1; fi
inp_command="${@:3}"
local n=1
while true; do
$inp_command && break || {
if [[ $n -lt $max ]]; then
((n++))
echo "Command failed. Attempt $n/$max:"
sleep $delay;
else
echo "The command has failed after $n attempts." >&2
return -1
fi
}
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment