windows 为什么我的设置命令没有存储任何内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14347038/
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
Why are my set commands resulting in nothing getting stored?
提问by gregturn
I am trying to access the value of TOMCAT_VER later on, but it appears as an empty string.
我稍后尝试访问 TOMCAT_VER 的值,但它显示为空字符串。
if exist "%_REALPATH%\tomcat-%TOMCAT_VER2%" (
set CATALINA_HOME=%_REALPATH%\tomcat-%TOMCAT_VER2%
set TOMCAT_VER=%TOMCAT_VER2%
echo "%TOMCAT_VER%"
) else if exist "%TOMCAT_VER2%" (
set CATALINA_HOME="%TOMCAT_VER2%"
set TOMCAT_VER="%TOMCAT_VER2%"
echo "%TOMCAT_VER%"
)
To further debug, I inserted an echo statement right below where it gets set, but it doesn't seem to work. With echo off disabled, I can see the statement showing these variables getting set, and yet I can't seem to print them out.
为了进一步调试,我在它设置的正下方插入了一个 echo 语句,但它似乎不起作用。禁用 echo off 后,我可以看到显示这些变量正在设置的语句,但我似乎无法将它们打印出来。
回答by jeb
You found the bbb (batch beginner bug), but not the variable is empty, it's the expansion that doesn't work as expected.
您找到了 bbb(批处理初学者错误),但不是变量为空,而是扩展未按预期工作。
Percent expansion is done when a line or a complete parenthesis block is parsed, before the code will be executed.
But to solve this you can use the delayed expansion, this doesn't expand at parse time, it expands just at execution time.
当解析一行或完整的括号块时,在执行代码之前完成百分比扩展。
但是要解决这个问题,您可以使用延迟扩展,它不会在解析时扩展,它只会在执行时扩展。
EnableDelayedExpansion adds an additional syntaxto expand variables: !var!
.
The percent expansion %var%
is still availabe and isn't changed by the delayed expansion.
The delayed expansion of !var!
is done when the expression is executed, in spite of %var%
, that will be expanded in the moment of parsing(complete code blocks), before any of the commands in the blocks are executed.
EnableDelayedExpansion添加了一个额外的语法来扩展变量:!var!
.
百分比扩展%var%
仍然可用,并且不会因延迟扩展而改变。
的延迟扩展!var!
是在执行表达式时完成的,尽管%var%
,它将在解析的时刻(完整代码块)进行扩展,在块中的任何命令被执行之前。
setlocal EnableDelayedExpansion
if exist "!_REALPATH!\tomcat-!TOMCAT_VER2!" (
set "CATALINA_HOME=!_REALPATH!\tomcat-!TOMCAT_VER2!"
set "TOMCAT_VER=!TOMCAT_VER2!"
echo !TOMCAT_VER!
) else if exist "!TOMCAT_VER2!" (
set "CATALINA_HOME=!TOMCAT_VER2!"
set "TOMCAT_VER=!TOMCAT_VER2!"
echo !TOMCAT_VER!
)