About
From the set help.
Articles Related
The problem
The current expansion happens when a text block is read, not when it is executed.
IF
Here below, you have the example of an immediate variable expansion with an if block The following code when running:
@echo off
set VAR=before
if "%VAR%" == "before" (
set VAR=after
if "%VAR%" == "after" (
echo It worked
) ELSE (
echo It didn't work
)
)
is equivalent / expanded to :
set VAR=before
if "before" == "before" (
set VAR=after
if "before" == "after" (echo It worked ) ELSE (echo It didn't work )
)
because the substitution of the variable occurs in the whole if block.
And the above script will output:
It didn't work
FOR
Here below, you have the example of an immediate variable expansion within a for block that try to set up a variable with all list of files (in this case: demo1.bat and demo2.bat).
@echo on
set LIST=
for %%i in (*) do set LIST=%LIST%;%%i
echo %LIST%
is equivalent / expanded to :
set LIST=
for %i in (*) do set LIST=;%i
set LIST=;demo1.bat
set LIST=;demo2.bat
echo ;demo2.bat
And the above script will output:
;demo2.bat
Solution
Delayed environment variable expansion allows to use a different character (the exclamation mark) to expand environment variables at execution time.
If delayed variable expansion is enabled, the above examples If example could be written as:
set VAR=before
if "%VAR%" == "before" (
set VAR=after
if "!VAR!" == "after" (
echo It worked
) ELSE (
echo It doesn't worked
)
)
and the above script will output:
It worked
Configuration
The support for delayed environment variable expansion is always disabled by default, but may be enabled/disabled via:
- the /V command line switch to CMD.EXE.