3

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?

1
  • 2
    I suggest you to review this post Commented Jul 23, 2014 at 13:43

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, it works! Could you recommend a page which describes this strange delayed expansion thing?
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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.