Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

variables expansion inside for in batch

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

Output:

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...