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

不羁岁月 提交于 2020-01-21 03:16:09

问题


[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:\Users\Administrator>set name=value & echo %name%
%name%

C:\Users\Administrator>echo %name%
value

C:\Users\Administrator>

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


回答1:


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!



回答2:


You can also use cmd /V /C (with /V to enable delayed expansion).
That is great to set an environment variable for just one command in Windows cmd.exe:

cmd /V /C "set "name=value" && echo !name!"
value

Note the usage of double-quotes in set "name=value" to avoid the extra space after value.
For instance, without double-quotes:

cmd /V /C "set name=value && echo '!name!'"
'value '

You would need to think to remove the space between value and &&:

cmd /V /C "set name=value&& echo '!name!'"
'value'

But using double-quotes makes the assignment more explicit.



来源:https://stackoverflow.com/questions/9888806/run-two-commands-in-one-windows-cmd-line-one-command-is-set-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!