Wednesday, April 01, 2009

Counting in for loop in dos batch

This is the default behaviour of a FOR loop:



@echo off
setlocal
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [%_tst%] & set /a _tst+=1)
echo Total = %_tst%
C:>demo_batch.cmd
[0]
[0]
[0]
[0]
[0]
Total = 5

Notice that when the FOR loop finishes we get the correct total, so the variable correctly increments, but during each iteration of the loop the variable is stuck at it's initial value of 0

The same script with EnableDelayedExpansion, gives the same final result but also displays the intermediate values:



@echo off
setlocal EnableDelayedExpansion
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [!_tst!] & set /a _tst+=1)
echo Total = !_tst!
C:\>demo_batch.cmd
[0]
[1]
[2]
[3]
[4]
Total = 5

Notice that instead of %variable% we use !variable!


http://www.ss64.com/nt/setlocal.html

No comments: