Set value of the variable in “FOR” loop in Window batch script

1:14 am Window

Running for loop and setting the variable values within the for loop is different in window batch file comparing to other scripting or programming language.

Following example is trying to get the total value of 1, 2, 3 and 4.

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

But we will get:

0
0
0
0

This is because batch processor expands the variable only once, thus %COUNT% is expanded to its value, which is the initial value, 0.

To fix this, ENABLEDELAYEDEXPANSION can be turned on to delay the batch processor expanding the variable the end of the looping. Also, using ! instead of % to expand the environment variable value.

setlocal ENABLEDELAYEDEXPANSION
set COUNT=0
for %%F in (1 2 3 4) do (
set /A COUNT=!COUNT! + %%F
echo !COUNT!
)

The result of the above code is:

1
3
6
10

There’s another way to enable the delay expansion is through the registry. Please refer to http://batcheero.blogspot.com/2007/06/how-to-enabledelayedexpansion.html.

Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.