Some of the solutions shown on this page will loop an infinite number of times if the command continues to fail.
If you're not a fan of infinite loops try this:
function retry {
command="$*"
retval=1
attempt=1
until [[ $retval -eq 0 ]] || [[ $attempt -gt 5 ]]; do
# Execute inside of a subshell in case parent
# script is running with "set -e"
(
set +e
$command
)
retval=$?
attempt=$(( $attempt + 1 ))
if [[ $retval -ne 0 ]]; then
# If there was an error wait 10 seconds
sleep 10
fi
done
if [[ $retval -ne 0 ]] && [[ $attempt -gt 5 ]]; then
# Something is fubar, go ahead and exit
exit $retval
fi
}
Now, whenever you need a retry loop, just run:
retry mycommand and args
e.g.:
retry ncftpput -DD -z -u user -p password remoteserver /remote/dir /local/file