bat file: variables have wrong value untill next execution of bat?
I'm reading a property from a .properties file (looks like: applocation=c:\x\y\z).
Using the line: 开发者_运维技巧FOR /F "eol=; tokens=2,2 delims==" %%i IN ('findstr /i "applocation" %1') DO set name=%%i
%1 is the location of the .property file that I pass as an argument.
After setting the property I do:
echo %applocation%
However the first time I execute the bat file it echoes the location from where I executed the bat file. Only after executing the bat file again from the same console window do I get the correct value.
This is quite peeving, especially since if I close the command window I have to do this all over again.
You're likely in a block of an if or another for
there, I guess, such as this:
if foo (
FOR /F "eol=; tokens=2,2 delims==" %%i IN ('findstr /i "applocation" %1') DO set name=%%i
echo %applocation%
)
This cannot work, as environment variables are expanded when parsing such a block, not when running it.
To use delayed expansion put
setlocal enabledelayedexpansion
at the top of your batch file and then use
if foo (
FOR /F "eol=; tokens=2,2 delims==" %%i IN ('findstr /i "applocation" %1') DO set name=%%i
echo !applocation!
)
Won't work. See Delayed Variable Expansion
精彩评论