Windows – For Loop counting from 1 to n in a windows bat script

batchscriptingwindows

I need to run a windows command n times within a bat script file. I know how to do this in various programming languages but cannot manage to get it right on the windows command line 🙁

I would expect something like either

for(int i = 0; i < 100; i++) {
   // do something
}

or even this (though not entirely seriously)

1.upto(100, {
   // do something
}) 

Thanks!

EDIT

I can write a program in java, perl, c or whatever that will generate a bat script that looks like this

for %%N in (1 2 3 4 5 6 7 8 9 10 11 12) do echo %%N

and so on. Or even "better":

echo 1
echo 2
echo 3
echo 4
echo 5
echo 6
echo 7
echo 8
echo 9
echo 10
echo 11
echo 12

and then execute it… But the thing is that I need a concise way to specify a range of numbers to iterate through within the script.

Thanks!

Best Answer

You can do it similarly like this:

ECHO Start of Loop

FOR /L %i IN (1,1,5) DO (
  ECHO %i
)

The 1,1,5 is decoded as:

(start,step,end)

Also note, if you are embedding this in a batch file, you will need to use the double percent sign (%%) to prefix your variables, otherwise the command interpreter will try to evaluate the variable %i prior to running the loop.