[windows] Batch script loop

I need to execute a command 100-200 times, and so far my research indicates that I would either have to copy/paste 100 copies of this command, OR use a for loop, but the for loop expects a list of items, hence I would need 200 files to operate on, or a list of 200 items, defeating the point.

I would rather not have to write a C program and go through the length of documenting why I had to write another program to execute my program for test purposes. Modification of my program itself is also not an option.

So, given a command, a, how would I execute it N times via a batch script?

Note: I don't want an infinite loop

For example, here is what it would look like in Javascript:

var i;
for (i = 0; i < 100; i++) {
  console.log( i );
} 

What would it look like in a batch script running on Windows?

This question is related to windows loops batch-file

The answer is


DOS doesn't offer very elegant mechanisms for this, but I think you can still code a loop for 100 or 200 iterations with reasonable effort. While there's not a numeric for loop, you can use a character string as a "loop variable."

Code the loop using GOTO, and for each iteration use SET X=%X%@ to add yet another @ sign to an environment variable X; and to exit the loop, compare the value of X with a string of 100 (or 200) @ signs.

I never said this was elegant, but it should work!


Not sure if an answer like this has already been submitted yet, but you could try something like this:

@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start

:end
echo var has reached %var%.
pause
exit

The variable %var% will increase by one until it reaches 100 where the program then outputs that it has finished executing. Again, not sure if this has been submitted or something like it, but I think it may be the most compact.


a completely flawless loop

set num=0
:loop
:: insert code
set num=%num%+1
if %num% neq 10 goto loop
::insert after code code

you can edit it by changing the 10 in line 5 to any number to represent how many time you want it to loop.


And to iterate on the files of a directory:

@echo off 
setlocal enableDelayedExpansion 

set MYDIR=C:\something
for /F %%x in ('dir /B/D %MYDIR%') do (
  set FILENAME=%MYDIR%\%%x\log\IL_ERROR.log
  echo ===========================  Search in !FILENAME! ===========================
  c:\utils\grep motiv !FILENAME!
)

You must use "enableDelayedExpansion" and !FILENAME! instead of $FILENAME$. In the second case, DOS will interpret the variable only once (before it enters the loop) and not each time the program loops.


I use this. It is just about the same thing as the others, but it is just another way to write it.

@ECHO off
set count=0
:Loop
if %count%==[how many times to loop] goto end
::[Commands to execute here]
set count=%count%+1
goto Loop
:end

Or you can decrement/increment a variable by the number of times you want to loop:

SETLOCAL ENABLEDELAYEDEXPANSION
SET counter=200
:Beginning
IF %counter% NEQ 0 (
echo %x
copy %x.txt z:\whatever\etc
SET /A counter=%counter%-1
GOTO Beginning
) ELSE (
ENDLOCAL
SET counter=
GOTO:eof

Obviously, using FOR /L is the highway and this is the backstreet that takes longer, but it gets to the same destination.


The answer really depends on how familiar you are with batch, if you are not so experienced, I would recommend incrementing a loop variable:

@echo off
set /a loop=1
:repeat
echo Hello World!
set /a loop=%loop%+1
if %loop%==<no. of times to repeat> (
goto escapedfromrepeat
)
goto repeat
:escapedfromrepeat
echo You have come out of the loop
pause

But if you are more experienced with batch, I would recommend the more practical for /l %loop in (1, 1, 10) do echo %loop is the better choice.

             (start at 1, go up in 1's, end at 10)
for /l %[your choice] (start, step, end) do [command of your choice]

You can do this without a for statement ^.^:

@echo off
:SPINNER
SET COUNTP1=1

:1
CLS
 :: YOUR COMMAND GOES HERE
IF !COUNTP1! EQU 200 goto 2

SET COUNTP1=1
) ELSE (
SET /A COUNTP1+=1
)
goto 1

:2
:: COMMAND HAS FINISHED RUNNING 200 TIMES

It has basic understanding. Just give it a test. :P


Template for a simple but counted loop:

set loopcount=[Number of times]
:loop
[Commands you want to repeat]
set /a loopcount=loopcount-1
if %loopcount%==0 goto exitloop
goto loop
:exitloop

Example: Say "Hello World!" 5 times:

@echo off
set loopcount=5
:loop
echo Hello World!
set /a loopcount=loopcount-1
if %loopcount%==0 goto exitloop
goto loop
:exitloop
pause

This example will output:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Press any key to continue . . .

Probbally use goto like

@echo off
:Whatever
echo hello world
pause
echo TEST
goto Whatever

This does a inf (infinite) loop.


Very basic way to implement looping in cmd programming using labels

@echo off
SET /A "index=1"
SET /A "count=5"
:while
if %index% leq %count% (
   echo The value of index is %index%
   SET /A "index=index + 1"
   goto :while
)

You could do something to the following effect avoiding the FOR loop.

set counter=0
:loop
echo "input commands here"
SET /A counter=%counter%+1
if %counter% GTR 200
(GOTO exit) else (GOTO loop)
:exit
exit

I have 2 answers Methods 1: Insert Javascript into Batch

@if (@a==@b) @end /*

:: batch portion

@ECHO OFF

cscript /e:jscript "%~f0"


:: JScript portion */

Input Javascript here

( I don't know much about JavaScript )

Method 2: Loop in Batch

   @echo off
    set loopcount=5
    :loop
    echo Hello World!
    set /a loopcount=loopcount-1
    if %loopcount%==0 goto exitloop
    goto loop
    :exitloop
    pause

(Thanks FluorescentGreen5)


Here is a template script I will use.

@echo off
goto Loop

:Loop
<EXTRA SCRIPTING HERE!!!!>
goto Loop

exit

What this does is when it starts it turns off echo then after that it runs the "Loop" but in that place it keeps going to "Loop" (I hope this helps.)


(EDITED) I made it so it stops after 100 times

@echo off
goto actual
set /a loopcount=0
:actual
set /a loopcount=%loopcount% + 1
echo %random% %random% %random% %random%
timeout 1 /nobreak>nul
if %loopcount%== 100 goto stop
goto actual
:stop
exit

This will generate 4 random numbers ever 1 second 100 times. Take out the "timeout 1 /nobreak>nul" to make it go super fast.


You could also try this instead of a for loop:

set count=0
:loop
set /a count=%count%+1
(Commands here)
if %count% neq 100 goto loop
(Commands after loop)

It's quite small and it's what I use all the time.


Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to batch-file

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH CanĀ“t run .bat file under windows 10 Execute a batch file on a remote PC using a batch file on local PC Windows batch - concatenate multiple text files into one How do I create a shortcut via command-line in Windows? Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat Curl not recognized as an internal or external command, operable program or batch file Best way to script remote SSH commands in Batch (Windows)