Example of delayed expansion in batch file

Look at the following examples…

Example 1: The following code DOESN’T use delayed expansion, so the variables in the for loop are expanded only one time. This means that %Count% will always expand to 0 in each iteration of the loop, no matter what we do to it with the set command:

@echo off
set COUNT=0

for %%v in (1 2 3 4) do (
  set /A COUNT=%COUNT% + 1
  echo Count = %COUNT%
)
pause

So this script will output:

Count = 0
Count = 0
Count = 0
Count = 0

This is not how this loop is supposed to work.

Example 2: On the other hand, if we use delayed expansion, we have the following script, which will run as expected.

setlocal ENABLEDELAYEDEXPANSION
set COUNT=0

for %%v in (1 2 3 4) do (
  set /A COUNT=!COUNT! + 1
  echo Count = !COUNT!
)

pause

and, as expected, it will output:

Count = 1
Count = 2
Count = 3
Count = 4

When you use the ENABLEDELAYEDEXPANSION, and expand a variable using ! instead of %, the variable is re-expanded each time, and everything works as it’s supposed to.

Leave a Comment