Sometimes you need to create a batch script, that maybe retries a couple of times doing something or maybe repeat the same task for a bunch of files, incrementing filenames or whatever you want. You then need to create a loop, because you don’t want your script to get 1000 or more lines long. So, here’s my 2c on how you correctly loop in windows batch files.
This is an easy example of a head-controlled loop. You may need to adapt it, butit is executable and I only want to show you the basics of doing so:
This is a very short one, without many remarks. GOTOs are ugly, but needed anyway. My examples make three loops and screen outputs of the current state. Remember the syntax and take care when you copy paste, that your quotes might get screwed up.
@ECHO OFF REM Reset counter SET /A COUNT="1" REM How often do you loop? SET /A BOUND="3" :LOOP IF %COUNT% GTR %BOUND% ( ECHO.END OF THE LOOP - EXITING... GOTO :END ) ELSE ( ECHO.We're inside loop pass number= %COUNT% SET /A COUNT=%COUNT%+1 ECHO.Counter value after the increment= %COUNT% GOTO :LOOP ) :END ECHO.Loop exited. PAUSE
So much about the head controlled one. Maybe you prefer the foot controlled loops (like do-while), but these are made to run at least once. Keep an eye on the different break conditions as well, one breaks the loop when counting greater than three, the other one when „no longer being less or equal to three“. The difference is simply that I always want the IF-statement to contain the lesser commands (maybe only the GOTO command) to keep it in a single line of code – this way I can save many ELSE-commands, because if we don’t jump, we continue anyway…
Anyhow, here the foot controlled loop:
@ECHO OFF SET /A COUNT="1" SET /A BOUND="3" :LOOP ECHO.We're inside loop pass number= %COUNT% SET /A COUNT=%COUNT%+1 ECHO.Counter value after the increment= %COUNT% IF %COUNT% LEQ %BOUND% ( GOTO :LOOP ) ELSE ( ECHO.END OF THE LOOP - EXITING... GOTO :END ) :END ECHO.Loop exited. PAUSE
You can replace this part:
IF %COUNT% LEQ %BOUND% ( GOTO :LOOP ) ELSE ( ECHO.END OF THE LOOP - EXITING... GOTO :END )
IF %COUNT% LEQ %BOUND% GOTO :LOOP ECHO.END OF THE LOOP - EXITING...
But in case you want to execute multiple commands before exiting, the else part in brackets may come in handy.
You could always work with command line variables to tell how many times to loop with the variable %1 – but that’s another topic.
How about your solutions on this topic?