Can anyone explain this? I am able to count in a loop using the Windows command prompt, using this method:
SET /A XCOUNT=0
:loop
SET /A XCOUNT+=1
echo %XCOUNT%
IF "%XCOUNT%" == "4" (
GOTO end
) ELSE (
GOTO loop
)
:end
But this method does not work (it prints out “1” for each line in the file). It acts like the variable is out of scope:
SET /A COUNT=1
FOR /F "tokens=*" %%A IN (config.properties) DO (
SET /A COUNT+=1
ECHO %COUNT%
)
It’s not working because the entire
forloop (from theforto the final closing parenthesis, including the commands between those) is being evaluated when it’s encountered, before it begins executing.In other words,
%count%is replaced with its value1before running the loop.What you need is something like:
Delayed expansion using
!instead of%will give you the expected behaviour. See also here.Also keep in mind that
setlocal/endlocalactually limit scope of things changed inside so that they don’t leak out. If you want to usecountafter theendlocal, you have to use a “trick” made possible by the very problem you’re having:Let’s say
counthas become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:Then, when it’s executed, the inner scope is closed off, returning
countto it’s original value. But, since the setting ofcountto seven happens in the outer scope, it’s effectively leaking the information you need.You can string together multiple sub-commands to leak as much information as you need: