[英]windows batch SET inside IF not working
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 var2
variable was not really set.这意味着没有真正设置
var2
变量。 Can anyone please help me understand why?谁能帮我理解为什么?
var2 is set, but the expansion in the line echo %var2%
occurs before the block is executed. var2 已设置,但
echo %var2%
行中的扩展发生在执行块之前。
At this time var2
is empty.此时
var2
为空。
Therefore the delayedExpansion syntax exists, it uses !
因此延迟扩展语法存在,它使用
!
instead of %
and it is evaluated at execution time, not parse time.而不是
%
,它是在执行时评估的,而不是解析时。
Please note that in order to use !
请注意,为了使用
!
, the additional statement setlocal EnableDelayedExpansion
is needed. ,需要附加语句
setlocal EnableDelayedExpansion
。
setlocal EnableDelayedExpansion
set var1=true
if "%var1%"=="true" (
set var2=myvalue
echo !var2!
)
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 goto
syntax或/和使用
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
.这种方式扩展“及时”发生,您不需要
setlocal EnableDelayedExpansion
。 Bottom line, if you rethink design of your script you can do it like that底线,如果您重新考虑脚本的设计,您可以这样做
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.