Alex Rivera | Logout

Batch file variables initialized in a for loop

Asked 2009-03-27T18:52:11.370
17

I have a batch file which initializes variables via SET inside a for loop, for a set of files on disk:

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

  echo In loop %TMPFILE%
)

echo End loop %TMPFILE%

when I run this in a brand new command shell (without TMPFILE defined) the In loop echo is empty, but the end loop echo is not.

When I run a second time, its already set, and outputs its value, ignoring the set until the loop closes.

Ideas why this is, and what the workaround is?

Edit
Report

1 Answer

9

That's because the ( ) block is parsed only once, it substitutes %TMPFILE% before it runs your loop.

answered 2009-03-27T19:01:07.213

Your Answer