Why are my set commands resulting in nothing getting stored?

夙愿已清 提交于 2019-12-17 16:19:36

问题


I am trying to access the value of TOMCAT_VER later on, but it appears as an empty string.

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.


回答1:


You found the bbb (batch beginner bug), but not the variable is empty, it's the expansion that doesn't work as expected.

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.

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!"
)


来源:https://stackoverflow.com/questions/14347038/why-are-my-set-commands-resulting-in-nothing-getting-stored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!