Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

windows - Batch file variables initialized in a for loop

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For the record, the corrected script looks like this:

setlocal ENABLEDELAYEDEXPANSION

for %%f in (%MYTARGETDIR%*config.xml) do (

  SET TMPFILE=%%F.tmp

  echo In loop !TMPFILE!
)

echo End loop %TMPFILE%

Thanks chris for your help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...