0

I have a for loop in a batch file. I get this weird behaviour with the counter variable. I am an experienced programmer, but a beginner in batch files.

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS

SET list=test1 test2 test3

FOR %%a IN (%list%) DO (
    SET variable=%%a
    ECHO %%a
    ECHO -%variable%-
)

I expect the output to be

test1
-test1-
test2
-test2-
test3
-test3-

but it actually is

test1
-test3-
test2
-test3-
test3
-test3-

What am I doing wrong?

Simone
  • 1,260
  • 1
  • 16
  • 27

1 Answers1

1

The actual expected output is

test1
--
test2
--
test3
--

I would be astonished to get anything else; I definitely cannot reproduce your output.

Variables are expanded only once, when the ( ... ) construction is read. If you want that the assignments inside ( ... ) to take effect within ( ... ) you need to setlocal enabledelayedexpansion and use !variable!. (Or, as some prefer, call a subroutine instead of using ( ... )).

AlexP
  • 4,370
  • 15
  • 15
  • Indeed that's what I got the first few times - it's possible that I somehow polluted the variable in a global scope? Anyway, your solution works, so I'm going to accept this answer. Thank you! – Simone Nov 15 '17 at 09:59