DOS and Batch Files

SET: Odd behavior in loops, not updating

When using the SET command in loops it can be seen that the variable is not updating properly.

@echo off
REM count to 3 storing the results in a variable
set tst=0
FOR /L %%f in (1,1,3) Do (set /a tst+=1 & echo. test %%f in loop = %tst%)
echo. Test outside the loop = %tst%

The result of this batch file is

test 1 in loop = 0
test 2 in loop = 0
test 3 in loop = 0
Test outside the loop = 3

Surely the variable tst should be increasing throught the loop?

The answer is that it is! But what happens is that variables are expanded or evaluated just once per command line so multi-line commands such as IF and FOR do not appear to evaluate properly but once the variable is seen outside of their structure the variable is correct.

By using SETLOCAL EnableDelayedExpansion and referencing the variable between ! marks in the loop then the variable now displays correctly...

@echo off
setlocal EnableDelayedExpansion
REM count to 3 storing the results in a variable
set tst=0
FOR /L %%f in (1,1,3) Do (set /a tst+=1 & echo. test %%f in loop = !tst!)
echo. Test outside the loop = %tst%

The result of this batch file is

test 1 in loop = 1
test 2 in loop = 2
test 3 in loop = 3
Test outside the loop = 3

This page created 30th December 2011, last modified 30th December, 2011


GoStats stats counter