DOS - Delayed environment variable

Card Puncher Data Processing

About

From the set help.

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:





Discover More
Card Puncher Data Processing
DOS - SETLOCAL and ENDLOCAL

Begins localization of environment changes in a batch file. Environment changes made after SETLOCAL has been issued are local to the batch file. ENDLOCAL must be issued to restore the previous settings....
Card Puncher Data Processing
Dos - (Batch) Script

The batch script is a text file with the extension .bat or .cmd that is interpreted by a batch interpreter. You can call a batch script by : writing its name in the source script: The script execution...
Card Puncher Data Processing
Dos - (Environment) Variable

How to manage variable in dos. A variable name: must only be made up of: alphabetic characters, numeric characters and underscores, cannot begin with a numeric character. cannot be...
Card Puncher Data Processing
Dos - Cmd (Command interpreter)

Cmd starts a new instance of the Windows command interpreter More info: The switches must be on one line but for the purpose of clarity we have put one switch by line. where: /Q turns echo off...



Share this page:
Follow us:
Task Runner