在一个Windows cmd行中运行两个命令,一个命令是SET命令 [英] run two commands in one windows cmd line, one command is SET command

查看:150
本文介绍了在一个Windows cmd行中运行两个命令,一个命令是SET命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[purpose]



这个简单的命令序列在Windows的CMD shell中运行:

  dir& echo hello 

将列出文件和目录并回显该字符串。



但是,以下命令序列不会按预期运行(至少由我):

  C :\Users\Administrator> set name = value& echo%name%
%name%

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

C:\Users \管理员>

我们可以看到,第一个echo不能得到环境。你能帮忙评论吗?

解决方案



div>

您的结果是由于%name%在解析阶段展开,并且整个行在设置值之前一次性解析。



您可以通过以下两种方式之一获得与set命令在同一行上的当前值。



1)使用CALL引起ECHO%NAME%第二次解析:

  set name = value& call echo%^ name%

我在一个百分比之间放了一个 ^ 被执行。如果没有插入符,您将得到旧的值。



注意:您的原始行在& ,则此空间将包含在变量的值中。您可以使用引号来防止额外的空格: setname = value& ...



2 )使用延迟扩展在执行时间而不是在解析时间获取值。大多数环境没有默认启用延迟扩展。您可以使用相应的CMD.EXE选项在命令行上启用延迟扩展。

  cmd / v:on 
setname = value& echo!name!

延迟扩展肯定可以在命令行中使用,但它在批处理文件。 SETLOCAL用于在批处理文件中启用延迟扩展(在命令行中不起作用)

  setlocal enableDelayedExpansion 
setname = value& echo!name!


[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

解决方案

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!

这篇关于在一个Windows cmd行中运行两个命令,一个命令是SET命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆