如果不工作,Windows 批处理 SET 内部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9102422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 09:10:35  来源:igfitidea点击:

windows batch SET inside IF not working

windowsbatch-filecmddelayedvariableexpansion

提问by Orad SA

when I'm running this script (from a .bat file):

当我运行这个脚本时(来自 .bat 文件):

set var1=true
if "%var1%"=="true" (
  set var2=myvalue
  echo %var2%
)

I always get:

我总是得到:

ECHO is on.

Meaning the var2variable was not really set. Can anyone please help me understand why?

这意味着var2变量并没有真正设置。谁能帮我理解为什么?

回答by jeb

var2 is set, but the expansion in the line echo %var2%occurs before the block is executed.
At this time var2is empty.

var2 已设置,但行中的扩展echo %var2%发生在块执行之前。
此时var2是空的。

Therefore the delayedExpansion syntax exists, it uses !instead of %and it is evaluated at execution time, not parse time.

因此,存在delayedExpansion 语法,它使用!代替而不是%在执行时而不是解析时进行评估。

Please note that in order to use !, the additional statement setlocal EnableDelayedExpansionis needed.

请注意,为了使用!setlocal EnableDelayedExpansion需要附加语句。

setlocal EnableDelayedExpansion
set var1=true
if "%var1%"=="true" (
  set var2=myvalue
  echo !var2!
)

回答by T.S.

I am a bit late to the party but another way to deal with this condition is to continue process outside if, like this

我参加聚会有点晚了,但另一种处理这种情况的方法是在外面继续处理if,就像这样

set var1=true
if "%var1%"=="true" (
    set var2=myvalue
)
echo %var2%

Or/and use gotosyntax

或/和使用goto语法

set var1=true
if "%var1%"=="true" (
    set var2=myvalue
    goto line10
) else (
    goto line20
)
. . . . .
:line10
echo %var2%
. . . . . 
:line20

This way expansion occurs "in time" and you don't need setlocal EnableDelayedExpansion. Bottom line, if you rethink design of your script you can do it like that

这样扩展会“及时”发生,您不需要setlocal EnableDelayedExpansion. 最重要的是,如果您重新考虑脚本的设计,您可以这样做