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
614 views
in Technique[技术] by (71.8m points)

run two commands in one windows cmd line, one command is SET command

[purpose]

This simple command sequence runs expected in the Windows' CMD shell:

dir & echo hello

will list the files and directories and echo the string.

However, the following command sequence does not run as expected (at least by me):

C:UsersAdministrator>set name=value & echo %name%
%name%

C:UsersAdministrator>echo %name%
value

C:UsersAdministrator>

As we can see, the first echo cannot get the environment. Could you help to comment? Any comment will be appreciated!

PS: OS:Windows 7 X64 Home Pre

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your result is due to the fact that %name% is expanded during the parsing phase, and the entire line is parsed at once, prior to the value being set.

You can get the current value on the same line as the set command in one of two ways.

1) use CALL to cause ECHO %NAME% to be parsed a 2nd time:

set name=value&call echo %^name%

I put a ^ between the percents just in case name was already defined before the line is executed. Without the caret, you would get the old value.

Note: your original line had a space before the &, this space would be included in the value of the variable. You can prevent the extra space by using quotes: set "name=value" &...

2) use delayed expansion to get the value at execution time instead of at parse time. Most environments do not have delayed expansion enabled by default. You can enable delayed expansion on the command line by using the appropriate CMD.EXE option.

cmd /v:on
set "name=value" & echo !name!

Delayed expansion certainly can be used on the command line, but it is more frequently used within a batch file. SETLOCAL is used to enable delayed expansion within a batch file (it does not work from the command line)

setlocal enableDelayedExpansion
set "name=value" & echo !name!

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

...