bash script: repeat command if it returns an error
I would like to create a loop that repeats a ncftp transfer if it returns an error.
I'm a little unsure how the exit code variable can be used in a loop. Would something like this work?
until [$? == 0]; do
ncftpput -DD -z -u user -p password remoteserver /remote/dir /local/file
done
Solution 1:
I found the basis for this elegant loop elsewhere on serverfault. Turns out there is no need save the exit code, as you can test directly on the command itself;
until ncftpput -DD -z -u user -p password remoteserver /remote/dir /local/file; do
echo Tansfer disrupted, retrying in 10 seconds...
sleep 10
done
Solution 2:
Almost. You are probably better saving the return value as a variable so that you can pre-set it before the loop. Otherwise it will be affected by the last-run command.
You might also want to sling a sleep
in there to stop it respawning too quickly.
RET=1
until [ ${RET} -eq 0 ]; do
ncftpput -DD -z -u user -p password remoteserver /remote/dir /local/file
RET=$?
sleep 10
done
Solution 3:
Bit hacky but my solution was to just create a bash function which runs itself if it exits with a failure
function retry { the_command_you_want && echo "success" || (echo "fail" && retry) }; retry