-3

When I try to reference this variable in my for loop, it doesn't reference the value correctly. It stays at the value it was set before the loop. I tested that. But it seems that it updates the variable, though. Which makes even less sense to me. I debugged the variable with the "set" command in the loop. And yes, the value updates, but referencing it in the for loop still results in the value.

set /a index=0
for %%f in (*.*) do ( 
    set /a index=index+1
    echo index: %index%
)
echo index: %index%`

console output:

index: 0
index: 0
index: 0
index: 0
index: 0
index: 0
index: 0
index: 0
index: 0
index: 0
index: 0
index: 0
index: 12
Gerhard
  • 22,678
  • 7
  • 27
  • 43
  • 2
    This question has been asked a multitude of times, basically on a daily base. Please use the search function to research your problem before posting duplicate questions. – Gerhard Sep 02 '22 at 12:16

1 Answers1

0

That's well documented behaviour in batch files with parenthesized blocks in for. The reason is that the value is evaluated at the parsing phase of the batch file.

To change the value of a variable inside a block, you need to either

  1. enable delayed expansion
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set /a index=0 
for %%f in (*.*) do (  
  set /a index+=1 
  echo index: !index! 
) 
echo final: !index!

or

  1. use a call to a subroutine to set the variable.
@echo off
set /a index=0 
for %%f in (*.*) do call :incindex
echo final: %index%
goto :eof

:incindex
set /a index+=1
echo %index%
goto :eof
PA.
  • 28,486
  • 9
  • 71
  • 95
  • 2
    _"That's well documented behaviour in batch files with blocks in for"_ Not quite in `for` blocks only, it is the case in any parenthesized block... – Gerhard Sep 02 '22 at 13:27
  • yep, a missing word, corrected. – PA. Sep 03 '22 at 10:22
  • 1
    What I am saying is that it is not only `for` parenthesized block, any parenthesized block is affected. So remove `for` from that statement. – Gerhard Sep 03 '22 at 10:37
  • I know, but in this specific question, the problem appears in the parenthesized block of after the for. – PA. Sep 03 '22 at 17:04