windows batch SET inside IF not working

WindowsBatch FileCmdDelayedvariableexpansion

Windows Problem Overview


when I'm running this script (from a .bat file):

set var1=true
if "%var1%"=="true" (
  set var2=myvalue
  echo %var2%
)

I always get:

ECHO is on.

Meaning the var2 variable was not really set. Can anyone please help me understand why?

Windows Solutions


Solution 1 - Windows

var2 is set, but the expansion in the line echo %var2% occurs before the block is executed.
At this time var2 is empty.

Therefore the delayedExpansion syntax exists, it uses ! instead of % and it is evaluated at execution time, not parse time.

Please note that in order to use !, the additional statement setlocal EnableDelayedExpansion is needed.

setlocal EnableDelayedExpansion
set var1=true
if "%var1%"=="true" (
  set var2=myvalue
  echo !var2!
)

Solution 2 - Windows

I am a bit late to the party but another way to deal with this condition is to continue process outside if, like this

set var1=true
if "%var1%"=="true" (
    set var2=myvalue
)
echo %var2%

Or/and use goto syntax

set var1=true
if "%var1%"=="true" (
    set var2=myvalue
    goto line10
) else (
    goto line20
)
. . . . .
:line10
echo %var2%
. . . . . 
:line20

This way expansion occurs "in time" and you don't need setlocal EnableDelayedExpansion. Bottom line, if you rethink design of your script you can do it like that

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOrad SAView Question on Stackoverflow
Solution 1 - WindowsjebView Answer on Stackoverflow
Solution 2 - WindowsT.S.View Answer on Stackoverflow