开发者

bat file: variables have wrong value untill next execution of bat?

开发者 https://www.devze.com 2023-02-13 22:25 出处:网络
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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消