SET window package inside IF does not work

when I run this script (from a .bat file):

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

I always get:

 ECHO is on. 

The value of var2 not really set. Can someone help me understand why?

+77
windows cmd batch-file delayedvariableexpansion
Feb 01 '12 at 20:01
source share
2 answers

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

Therefore, delayedExpansion syntax exists, it uses ! instead of % , it is evaluated at runtime, not during parsing.

Please note that in order to use ! The optional setlocal EnableDelayedExpansion statement is setlocal EnableDelayedExpansion .

 setlocal EnableDelayedExpansion set var1=true if "%var1%"=="true" ( set var2=myvalue echo !var2! ) 
+139
Feb 01 '12 at 20:12
source share

I was a bit late for the party, but another way to deal with this condition is to continue the process on the street, 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, the extension happens "on time" and you do not need setlocal EnableDelayedExpansion . As a result, if you rethink the design of your script, you can do it like this

+1
Mar 27 '18 at 21:14
source share



All Articles