更新时间:2022-10-15 16:02:56
解析器有不同的阶段,解析一行时。结果
因此,前百分之pressions都在一条线或块被解析,则执行线路(或在块中的任何行)之前展开。
因此,在执行时,他们无法更改。
组VAR =由来
回声#1%VAR%
(
组VAR =新价值
回音2%VAR%
)
回声#3%VAR%
它输出
#1由来
#2原点
#3新的价值
由于在分析时#2将扩大到原产地
块的任意行之前执行。
所以,你可以在#3块之后看到新的数值。
在此相反,推迟扩张扩大了执行行之前的每一行。
SETLOCAL EnableDelayedExpansion
组VAR =由来
回声#1%VAR%!VAR!
(
组VAR =新价值
回音2%VAR%!VAR!
)
回声#3%VAR%!VAR!
输出
#1起源,起源
#2原点,新的价值
#3新的价值,新价值
现在在#2你看到同一个变量两个不同的扩展,因为当块被解析%VAR%扩大,但!无功!
终止后展开行组VAR =新值
被执行了。
有关批处理解析器在SO:如何在Windows命令国米preTER(CMD.EXE)解析脚本?
I am trying to learn MS Batch, and I was specifically trying to understand the "setlocal" and the "enabledelayedexpression" aspects, when I came across vocabulary I did not understand:
execution time and parse time
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?