0

I would like to know if it's possible or other ways to get this:

 @echo off
 setlocal enableDelayedExpansion
 SET loopcount=3

 SET variable1=test1
 SET variable2=test2
 SET variable3=test3

 for /l %%x in (1, 1, %loopcount%) do {
      echo %variable%%x%
 }

As you can see in echo, I want to get the value of variable1 which is test1 and so on... Is there any workaround on this? Thank you.

2
  • Try call echo %%variable%%x%% or echo !variable%%x! Commented Mar 16, 2021 at 12:04
  • or even: For /L %%x in (1 1 3)Do For /F "Tokens=2* Delims==" %%G in (' Set "Variable%%x" 2^> nul ')Do Echo(%%G Commented Mar 16, 2021 at 16:09

1 Answer 1

1

The best way to perform your task, is to use delayed expansion.

In your example you already enabled it, but didn't use it. A delayed variable is enclosed within ! characters, as opposed to % characters.

Example:

@Echo Off
SetLocal EnableExtensions EnableDelayedExpansion
Set "loopcount=3"

Set "variable1=test1"
Set "variable2=test2"
Set "variable3=test3"

For /L %%G In (1,1,%loopcount%) Do (
    Echo(!variable%%G!
)

However, you should wherever possible, you should only enable delayed expansion, when needed:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "loopcount=3"

Set "variable1=test1"
Set "variable2=test2"
Set "variable3=test3"

For /L %%G In (1,1,%loopcount%) Do (
    SetLocal EnableDelayedExpansion
    Echo(!variable%%G!
    EndLocal
)
Sign up to request clarification or add additional context in comments.

1 Comment

@DockerJava-Guy, if this is the best answer, please select the check mark to indicate that to other people. This is how SO works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.