According to the post How does the Windows Command Interpreter (CMD.EXE) parse scripts? (see phase 5), the line echo !!CLs[!count!]!!
cannot work, because the opening !!
are collapsed to a single !
, then !CLs[!
is expanded to an empty string (assuming such variable is not defined), then count
is returned literally, then !]!
is expanded to an empty string and the final !
is dismissed. Or in other words, delayed expansion cannot be nested.
You can use call
though to introduce another parsing phase, like this:
call echo %%CLs[!count!]%%
The line IF NOT %%I == CLs[!count!] ( ... )
is wrong, you must expand the right value too. However, call if
will not help unfortunately, because if
(like for
and rem
) is a special command that is recognised by the parser earlier than others, like call
.
To work around that you can store the value of !count!
in a for
meta-variable, like %%J
, for instance, to introduce another parsing phase, and use !CLs[%%J]!
then, like this:
set /A "count=0"
for /F "tokens=5" %%I in ('some command') do (
for %%J in (!count!) do (
echo !CLs[%%J]!
if not "%%I" == "!CLs[%%J]!" (
set /A "count+=1"
set "CLs[!count!]=%%I"
)
)
)
Another yet slower possibility is to put the relevant code into a sub-routine:
set /A "count=0"
for /F "tokens=5" %%I in ('some command') do (
call :SUB !count!
)
goto :EOF
:SUB
echo !CLs[%~1]!
if not "%%I" == "!CLs[%~1]!" (
set /A "count+=1"
set "CLs[%~1]=%%I"
)
goto :EOF
You may also take a look at the post Arrays, linked lists and other data structures in cmd.exe (batch) script about how to deal with such pseudo-arrays.