2

In windows, I want to loop over a set of environment variables like in this pseudo code:

set MYVAR1=test
set MYVAR2=4711
set MYVAR3="a b c"

for /l %%x in (1, 1, 3) do (
   echo %MYVAR%s%%
)

for which I expect the following output

test
4711
a b c 

How to change this example code to get it to work?

Alex
  • 41,580
  • 88
  • 260
  • 469
  • 2
    I suggest you to review [this post](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Jul 23 '14 at 13:43

3 Answers3

5
@echo off
set MYVAR1=test
set MYVAR2=4711
set MYVAR3="a b c"

setlocal enableDelayedExpansion
for /l %%x in (1, 1, 3) do (
   echo !MYVAR%%x!
)
endlocal
npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • 1
    Perfect, it works! Could you recommend a page which describes this strange delayed expansion thing? – Alex Jul 23 '14 at 11:30
  • 1
    here : http://ss64.com/nt/delayedexpansion.html and here : http://www.robvanderwoude.com/variableexpansion.php – npocmaka Jul 23 '14 at 11:36
2

One more way, parse the output of set command using the variable prefix

@echo off
    setlocal enableextensions disabledelayedexpansion

    set MYVAR1=test
    set MYVAR2=4711
    set MYVAR3="a b c"

    for /f "tokens=1,* delims==" %%a in ('set MYVAR') do echo %%b
MC ND
  • 69,615
  • 8
  • 84
  • 126
1

Another method:

@echo off
set MYVAR1=test
set MYVAR2=4711
set MYVAR3="a b c"

for /l %%x in (1, 1, 3) do (
   call echo %%MYVAR%%x%%
)
pause
foxidrive
  • 40,353
  • 10
  • 53
  • 68