Windows – Batch script loop

batch-fileloopswindows

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?

Best Answer

for /l is your friend:

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

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

Use two %s if it's in a batch file

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:
/l denotes that the for command will operate in a numerical fashion, rather than operating on a set of files
%x is the loops variable
(starting value, increment of value, end condition[inclusive] )