I have a batch file that calls various commands, some of which will occasionally fail due to network issues. Re-trying the command will usually result in success.
How can I re-try the commands automatically, up to a set number of tries?
Here is the some pseudo code that aims to explain further
call:try numTries "command and arguments"
exit
:try
REM execute %2, trying upto %1 times if it fails
%1 = %1 -1
eval %2
if %errorlevel%==0 exit \B
if %1 > 0 goto try
exit \B
The following script be be what you are looking for:
CALL :try numTries "command and arguments"
GOTO :EOF
:try
SET /A tries=%1
:loop
IF %tries% LEQ 0 GOTO return
SET /A tries-=1
EVAL %2 && (GOTO return) || (GOTO loop)
:return
EXIT /B
The logic of the try sub-routine is this:
Store the number of tries into a variable.
Begin the loop. Check the tries variable. If 0 or less, return.
Evaluate the command and arguments.
If the returned value is 'success' (ERRORLEVEL is 0), return (from the try routine), otherwise go to #2 (the beginning of the loop).
without eval and > (pretty much copy pasta of MatsT's answer)
REM execute %2, trying upto %1 times if it fails
set count=%1
set command=%2
:DoWhile
if %count%==0 goto EndDoWhile
set /a count = %count% -1
call %command%
if %errorlevel%==0 goto EndDoWhile
if %count% gtr 0 goto DoWhile
:EndDoWhile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With