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

4 comments:

Anonymous said...

我想了解新竹搬家公司的服務項目。

Anonymous said...

大拓的二十年的裝潢技術是無人能比的說。

Anonymous said...

我在煩腦汽車借款的問題,有人能幫忙嗎?

Anonymous said...

還有香舖工廠來尋找事業的第二春。