问题描述
我是新来的一批,我不明白什么时候使用后期变量扩展或正常扩张。下面我有一个测试脚本中,我已经测试过的变量扩展。我注意到里面,只是推迟扩建工程。不过,我想用正常的扩张内进行。
I am new to batch and I don't understand when to use late variable expansion or normal expansion. Below I have a test script in which I have tested the variables expansion. I have noticed that inside for, only delayed expansion works. However I would like to use normal expansion inside the for.
@echo off
setlocal
set var=0
echo late var=!var!
echo var=%var%
for /F "delims= " %%A in (temp.txt) do (
echo Analyzing %%A
set line=%%A
echo line=%line%
echo late line=!line!
)
endlocal
输出:
late var=0
var=0
Analyzing bb
line=
late line=bb
Analyzing aa
line=
late line=aa
Analyzing cc
line=
late line=cc
为什么我的只有延迟扩展以及如何使用内部的正常扩张?
谢谢你。
Why do I have in for only delayed expansion and how can I use normal expansion inside the for?Thanks.
推荐答案
在一条线或code(在code在括号括起来的块你的为
,达到如果
,...),解析器会删除所有变量读取,用线/块开始执行之前,变量中的值替换它们。所以,如果一个变量的值是线/块内改变,因为对变量内容的所有访问已被替换为它的值这个变化的值不是同一行/块内部可见。
When a line or a block of code (the code enclosed in parenthesis in your for
, if
, ... ) is reached, the parser removes all variable reads, replacing them with the value inside the variable before the line/block starts to execute. So, if the value of a variable is changed inside a line/block, this changed value is not visible inside that same line/block since all access to the variable content has been replaced with its value.
因此,如果该变量的值是一条线/块内改变,并且需要被读出的变量的改变值/在同一行/块内访问,需要延迟扩展
So, if the value of the variable is changed inside a line/block AND the changed value of the variable needs to be read/accessed inside the same line/block, delayed expansion is needed.
为
和如果
命令的地方,这通常是更加明显,但由于构造
for
and if
commands are places where this is usually more evident, but constructs as
set "data=test"
....
set "data=other test" & echo %data%
示出了同样的问题。当分析器处理的最后一行,%数据%
将替换它的值,然后执行线。因此,执行的最后一行是
shows the same problem. When the parser handles the last line, %data%
is replaced with its value, and then the line is executed. So the final line executed is
set "data=other test" & echo test
这篇关于扩展变量里面批量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!