lit
lit

Reputation: 16236

Setting and environment variable inside IF block

Setting the value of environment variable BOOBOO inside the if block does not appear to set it. However, it is set after the if block ends. Why does it not have a value inside the if block?

Running on Microsoft Windows XP [Version 5.1.2600] SP3

echo BOOBOO is +++%BOOBOO%+++
echo step 1
setlocal enableextensions
IF "%BOOBOO%" == "" (
    echo step 2
    SET BOOBOO=xyz
    echo step 3
    echo BOOBOO has been set to %BOOBOO%
    echo BOOBOO part is %BOOBOO:~0,2%
    echo step 4
)
echo step 8
echo BOOBOO ends up as %BOOBOO%
echo step 9
EXIT /B 0

===

M:> t
BOOBOO is ++++++
step 1
step 2
step 3
BOOBOO has been set to
BOOBOO part is ~0,2
step 4
step 8
BOOBOO ends up as xyz
step 9

Upvotes: 0

Views: 172

Answers (1)

dbenham
dbenham

Reputation: 130819

The value is set within the IF block, but you cannot see the change using normal expansion because the value is expanded at parse time, and the entire block is parsed at once before the IF command is executed. So you are getting the value that existed before you entered the IF block.

You have already enabled delayed expansion. You just need to use it.

echo BOOBOO has been set to !BOOBOO!
echo BOOBOO part is !BOOBOO:~0,2!

Upvotes: 1

Related Questions