1

I have a basic question. Struggling with setting variables within a if () bloc.

Below is my code.

@echo off 
setlocal 

set var1=variable1
set var1a=%var1%
echo expecting 'variable1' is %var1a%

if 1==1 (
        
    set var2=variable2
    set var2a=%var2%
    echo expecting 'variable2' %var2a%  
)

The output is

expecting 'variable1' is variable1
expecting 'variable2'

How come echo %var2% does give an output of variable2.

Is there some basic principle I am missing?

zoomraider
  • 117
  • 1
  • 9
  • 1
    Within a parenthesised series of instructions (aka "code block") any `%var%`, including `%errorlevel%`, is replaced by the then-current ("parse time") value of that variable when the block syntax is being validated. The syntax `if [not] errorlevel n` may be used, meaning `if the CURRENT errorlevel is [not] "n" OR GREATER THAN "n"`. Otherwise, `delayedexpansion` and `!var!` needs to be used to access the *current* value of the variable, including magic variables like *errorlevel time date cd* and others. [delayed expansion trap](https://stackoverflow.com/a/30284028/2128947) – Magoo Feb 03 '21 at 09:44

1 Answers1

0

try like this:

@echo off 
setlocal enableDelayedExpansion

set var1=variable1
set var1a=%var1%
echo expecting 'variable1' is %var1a%

if 1==1 (
        
    set var2=variable2
    set var2a=!var2!
    echo expecting 'variable2' !var2a!
)

more on delayed expansion: https://ss64.com/nt/delayedexpansion.html

npocmaka
  • 55,367
  • 18
  • 148
  • 187