Batch script loop
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.
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.
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 . . .
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.
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:/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] )