我正在尝试学习 MS Batch,当我遇到我不理解的词汇时,我特别想了解“setlocal”和“enabledelayedexpression”方面:
执行时间和解析时间
我正在尝试学习 MS Batch,当我遇到我不理解的词汇时,我特别想了解“setlocal”和“enabledelayedexpression”方面:
执行时间和解析时间
The parser has different phases, when parsing a single line.
So the percent expressions are all expand when a line or block is parsed, before the line (or any line in a block) is executed.
So at execution time they can't change anymore.
set var=origin
echo #1 %var%
(
set var=new value
echo #2 %var%
)
echo #3 %var%
It outputs
#1 origin
#2 origin
#3 new value
As at parse time #2 will be expanded to origin
before any line of the block is executed.
So you can see the new value just after the block at #3.
In contrast, delayed expansion is expanded for each line just before the line is executed.
setlocal EnableDelayedExpansion
set var=origin
echo #1 %var%, !var!
(
set var=new value
echo #2 %var%, !var!
)
echo #3 %var%, !var!
Output
#1 origin, origin
#2 origin, new value
#3 new value, new value
Now at #2 you see two different expansions for the same variable, as %var% is expanded when the block is parsed, but !var!
is expanded after the line set var=new value
was executed.
More details about the batch parser at SO: How does the Windows Command Interpreter (CMD.EXE) parse scripts?