windowsloopsfor-loopbatch-file

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, so 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:

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

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


Solution

  • for /l is your friend:

    for /l %x in (1, 1, 100) do echo %x
    

    Starts at 1, increments by one, and finishes at 100.

    WARNING: Use %% instead of %, if it's in a batch file, like:

    for /l %%x in (1, 1, 100) do echo %%x
    

    (which is one of the things I really really hate about windows scripting.)

    If you have multiple commands for each iteration of the loop, do this:

    for /l %x in (1, 1, 100) do (
       echo %x
       copy %x.txt z:\whatever\etc
    )
    

    or in a batch file:

    for /l %%x in (1, 1, 100) do (
       echo %%x
       copy %%x.txt z:\whatever\etc
    )
    

    Key: