SoFunction
Updated on 2025-04-08

How to use delayed expansion of variables in DOS batch processing (explained with simple version)

How to use variable delay scaling

Before using variable delay expansion, variable delay expansion features that need to be enabled
Get the delayed variable value. You need to add "!" on both sides of the variable name, instead of "%" (use "%" when expanding the variable)

How to enable variable delay expansion features

The variable delay expansion feature is turned off by default. There are currently two ways to enable it:

1. In the command line environment, use the "/v:on" command, which will open a new command line environment. The variable delay expansion feature is always valid before using the "/v:off" command to open a new command line environment (or use exit to exit). Examples are as follows:

C:\>cmd /v:off
Microsoft Windows [Version 6.1.7601]
all rights reserved (c) 2009 Microsoft Corporation。All rights reserved。
C:\>set first=1
C:\>set first=2 && echo %first%
1
C:\>cmd /v:on
Microsoft Windows [Version 6.1.7601]
all rights reserved (c) 2009 Microsoft Corporation。All rights reserved。
C:\>echo %first%
2
C:\>set first=3 && echo %first%
2
C:\>echo %first%
3
C:\>set first=4 && echo !first!
4
C:\>

2. In a batch file, in one of the following two local spaces:

In the local space between the commands "setlocal EnableDelayedExpansion" and "endlocal"
In the local space between "setlocal EnableDelayedExpansion" and the end of the batch file, it will

Automatically enabled variable delay expansion feature

Modifications to variables are restricted to this local space
That is, after the "endlocal" command (or exiting the batch file), the variable delay expansion characteristics and the modifications made to the variable in that local space will disappear together.

Example

The contents are as follows:

::
@echo off
set var=out
setlocal EnableDelayedExpansion
set var=one
for %%a in () do ( 
set var=two
echo !var! 
for %%a in () do ( 
echo !var! 
set var=three
echo !var! 
)
) 
endlocal
echo !var! 
echo %var% 

run

C:\>demo
two
two
three
!var!
out
C:\>

If you want to know moreDetailed explanation of enabledelayedexpansionYou can refer to this article

This is the article about how to use the delay extension of variables in DOS batch processing (explained with simple version). For more related DOS delay extension content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!