«

»

Jul
16

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

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.

Permanent link to this article: http://lindaocta.com/?p=337

Leave a Reply

Your email address will not be published.

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