Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I call batch command multiple times until success?

Tags:

batch-file

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
like image 411
Craig Avatar asked Oct 26 '25 15:10

Craig


2 Answers

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:

  1. Store the number of tries into a variable.

  2. Begin the loop. Check the tries variable. If 0 or less, return.

  3. Evaluate the command and arguments.

  4. If the returned value is 'success' (ERRORLEVEL is 0), return (from the try routine), otherwise go to #2 (the beginning of the loop).

like image 188
Andriy M Avatar answered Oct 29 '25 06:10

Andriy M


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
like image 31
gabriel Avatar answered Oct 29 '25 06:10

gabriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!