nested For Loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
gprashcom
Posts: 1
Joined: 19 Aug 2008 03:20

nested For Loop

#1 Post by gprashcom » 19 Aug 2008 03:27

Hiya,

I am stuck with a nested for loop and variable assignement, I am trying to do the following :-

SET /a COUNT=1

IF 2 NEQ 0 (
FOR /L %%G IN (1,1,2) DO (
REM ECHO %%G
ECHO %COUNT%
FOR /F "tokens= %COUNT%-2delims=$" %%A IN ("AAA$BBB%") DO (
ECHO %%A
set /a COUNT+=1
ECHO %COUNT%
)
)
)

But the COUNT variable never seems to be incremented and always has value of 1! Could anyone please help?

Thanks for your time..

P!

DosItHelp
Expert
Posts: 239
Joined: 18 Feb 2006 19:54

#2 Post by DosItHelp » 28 Aug 2008 20:25

gprashcom,

Don't worry, many have run into this problem before you.
The command interpreter substitutes variables before executing a block. The whole for loop is considered a block. By escaping the percent signs and CALL the command is forced to evaluate %COUNT% within the loop.

Use this line within the loop and you are fine:

Code: Select all

call echo %%COUNT%%

There are other ways, i.e.: enable delayed expansion at the beginning of you batch file and use "!" instead of "%" around a variable.

Code: Select all

SETLOCAL ENABLEDELAYEDEXPANSION
...
for ... (
    echo !COUNT!
)


DosItHelp? :wink:

Post Reply