Page 1 of 1

nested For Loop

Posted: 19 Aug 2008 03:27
by gprashcom
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!

Posted: 28 Aug 2008 20:25
by DosItHelp
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: