Classic for-loop in a windows batch file
Question: How can a classic for loop
for (int i=0;i<10;++i) {
// do stuff
}
be realized in a windows batch file?
Answer:
echo off
SET /a i=0
:loop
IF %i%==10 GOTO END
echo This is iteration %i%.
SET /a i=%i%+1
GOTO LOOP
:end
echo That’s it!
The answer uses goto and the /A option of the set command. Without that option, SET interprets the right side of the equals sign as a string and i would contain ‘i+1′, then ‘i+1+1′ and so on. To make SET interpret the right side as an arithmetic operation, the option /A is required. Enter SET /? to get a detailed explanation of the SET command’s capabilities.
March 19th, 2009 at 10:27 am
Thanks very much.
March 26th, 2009 at 1:24 pm
The arthametic is very starnge. Its working out side of loop but not working inside the loop
Here is my code : (Retrive.bat)
set i=1
echo %i%
set /a i = %i% + 1
echo %i%
for /r %%x in (%1) do (
set /a i = %i% + 1
echo %i%
copy /-y “%%x” %2%i%
:: all files with same name, so i need to append a counter
)
output :
D:\zzz>Retrive *.html d:\zzz\*.html
D:\zzz>set i=1
D:\zzz>echo 1
1
D:\zzz>set /a i = 1 + 1
D:\zzz>echo 2
2
D:\zzz>for /R %x in (*.html) do (
set /a i = 2 + 1
echo 2
copy /-y “%x” d:\zzz\*.html2
)
D:\zzz>(
set /a i = 2 + 1
echo 2
copy /-y “D:\zzz\CN=dashdash.html” d:\zzz\*.html2
)
2
Overwrite d:\zzz\CN=dashdash.html2? (Yes/No/All):
I am expecting i to be 3 …but ist still 2
March 29th, 2009 at 8:02 pm
Hi Aditya!
Now that’s an interesting question. Basically, the problem is, that SET does not work correct within for loops. At least not by default.
Basically, what you need to do is to start your shell with the parameter /V which enables “delayed environment variable expansion”. You can find more about that by typing “cmd /?”.
The other thing you need to do is to replace every occurence of “%i%” inside your loop with “!i!”. Type “set /?” to see a few examples and more explanation on delayed environment variable expansion.
That topic would be worth a post if there weren’t such a good one already:
http://www.robvanderwoude.com/variableexpansion.php
HTH!
Tom
January 17th, 2010 at 7:17 pm
Thanks, this snippet is very handy
September 28th, 2011 at 10:40 pm
Here’s two more versions:
——-%
September 28th, 2011 at 10:41 pm
Here’s two more versions:
—————————
@echo off
@FOR /L %%i in (0,1, 9) DO (
echo This is iteration %%i.
echo This is still iteration %%i
)
echo That’s it!
—————————
And my new favorite:
—————————
::MAIN ROUTINE
@FOR /L %%i in (0,1, 9) DO @CALL :PROCESS %%i
echo That’s it!
GOTO END
:: SUBROUTINE PROCESS
:PROCESS
echo This is iteration %1.
echo This is still iteration %1
GOTO:EOF
:END
—————————