windows batch SET inside IF not working

86,861

Solution 1

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

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

Share:
86,861

Related videos on Youtube

Orad SA
Author by

Orad SA

Updated on July 22, 2022

Comments

  • Orad SA
    Orad SA almost 2 years

    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?

  • Myna
    Myna about 11 years
    Thanks you just spared me a huge pain.
  • gwarah
    gwarah almost 5 years
    Same rule to & and &&operators. This code set x=some & set y=%x%thing & echo results %y% outputs %x%thing.
  • AntonioCS
    AntonioCS almost 4 years
    I am unable to access a variable I created inside an if statement. Your first example with var2 does not work.
  • T.S.
    T.S. almost 4 years
    @AntonioCS interesting... this is exact script that I just tested echo off set var1=true if "%var1%"=="true" ( set var2=myvalue ) echo %var2% pause.. and it is working. "if you will create a variable in the batch file that it can be accessed anywhere in the program.". aticleworld.com/batch-file-variables-and-scope