简体   繁体   中英

Call variable in for loop - BATCH

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.

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM