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

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

问题描述

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

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:操作系统:Windows 7 X64 Home Pre

PS: OS:Windows 7 X64 Home Pre

推荐答案

你的结果是因为 %name% 在解析阶段被扩展了,并且在设置值之前立即解析了整行.

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.

您可以通过以下两种方式之一在与 set 命令相同的行中获取当前值.

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

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

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.

注意:您的原始行在 & 之前有一个空格,该空格将包含在变量的值中.您可以使用引号来防止多余的空格: set "name=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) 使用延迟扩展在执行时而不是在解析时获取值.大多数环境默认没有启用延迟扩展.您可以使用适当的 CMD.EXE 选项在命令行上启用延迟扩展.

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!

在命令行中当然可以使用延迟扩展,但在批处理文件中使用更频繁.SETLOCAL 用于在批处理文件中启用延迟扩展(在命令行中不起作用)

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天全站免登陆