0

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

1 Answer 1

1

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!
Sign up to request clarification or add additional context in comments.

1 Comment

I thought delayed expansion was only used in FOR loops. Many thanks for the quick, correct answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.