Created
June 15, 2011 09:05
-
-
Save unakatsuo/1026755 to your computer and use it in GitHub Desktop.
bash retry function
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
# Run 10 times at most. | |
# % retry 10 echo "xxx" | |
# | |
# Run multiple lines of command in here document. | |
# % retry 10 <<'_END_' | |
# echo 1 | |
# echo 2 | |
# _END_ | |
function retry { | |
typeset retry_max=$1 | |
shift | |
typeset cmdlst="" i | |
if [[ -t 0 ]]; then | |
cmdlst="$*" | |
else | |
read -u 0 -d '' i | |
cmdlst="$i" | |
fi | |
typeset count=$retry_max | |
while [[ "$count" -gt 0 ]]; do | |
eval "$cmdlst" && break | |
count=$(($count - 1)) | |
sleep 1 | |
done | |
[[ "$count" -eq 0 ]] && { | |
echo "Retry failed [$retry_max]: ${cmdlst}" >&2 | |
return 1; | |
} | |
return 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment