2

I just had something completely bizarre come up, and I was wondering if this was expected behavior or if I've found some sort of strange bug in batch file processing. Without going into the details of what I'm trying to do, below is an example script that shows the behavior I'm talking about.

More or less, what I'm experiencing is that global environment variables that are set inside of a function call that is called from inside a if statement don't actually get set until the if statement exits!

@echo off
set myvar=1

echo %myvar% (should be 1)

if [%fakevar%] == [] (
    call:setEnvVars
    echo %myvar% (should be 2^) 
)
echo %myvar% (should be 2)

:setEnvVars
    set myvar=2
GOTO:EOF

The output is as follows:

1 (should be 1)
1 (should be 2)
2 (should be 2)

So, to reiterate, is this expected behavior (and why)? Or have I run into some sort of bug?

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Anthony
  • 245
  • 1
  • 2
  • 10

1 Answers1

4

Your issue have no relation to if command, but to Delayed Expansion. Try this example:

@echo off
set myvar=1
echo %myvar%  & set myvar=2 & echo %myvar%

and compare it vs. this one:

@echo off
setlocal EnableDelayedExpansion
set myvar=1
echo %myvar% & set myvar=2 & echo !myvar!

For further details, search for "Delayed Expansion" in this forum and/or read the explanation in set /? command help.

Aacini
  • 65,180
  • 12
  • 72
  • 108