Friday, April 3, 2009

Batch file variables modified and referenced in a for loop

More batch fun...

When a batch file executes and a loop is entered, the entire loop is parsed one time, and all variable references are expanded at that time. Supposedly this is for performance reasons, which is good because there are a lot of high-throughput batch files out there :)

So for example (from my stack overflow question):


for %%f in (%MYTARGETDIR%\*config.xml) do (
SET TMPFILE=%%F.tmp
echo In loop %TMPFILE%
)


does not show a value for the TMPFILE variable.

This can be overridden using enabedelayedexpansion:


setlocal ENABLEDELAYEDEXPANSION
for %%f in (%MYTARGETDIR%*config.xml) do (
SET TMPFILE=%%F.tmp
echo In loop !TMPFILE!
)

No comments: