【问题标题】:Call variable in for loop - BATCH在 for 循环中调用变量 - BATCH
【发布时间】:2021-06-13 16:48:24
【问题描述】:

我想知道是否有可能或其他方式得到这个:

 @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%
 }

正如您在 echo 中看到的那样,我想获取 variable1 的值,即 test1 等等......有什么解决方法吗?谢谢。

【问题讨论】:

  • 试试call echo %%variable%%x%%echo !variable%%x!
  • 甚至:For /L %%x in (1 1 3)Do For /F "Tokens=2* Delims==" %%G in (' Set "Variable%%x" 2^> nul ')Do Echo(%%G

标签: batch-file variables cmd


【解决方案1】:

执行任务的最佳方式是使用延迟扩展。

在您的示例中,您已经启用它,但没有使用它。延迟变量包含在 ! 字符内,而不是 % 字符内。

例子:

@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!
)

但是,您应该尽可能只在需要时启用延迟扩展:

@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
)

【讨论】:

  • @DockerJava-Guy,如果这是最佳答案,请选中复选标记以向其他人表明这一点。这就是 SO 的工作原理。
猜你喜欢
  • 2019-07-05
  • 1970-01-01
  • 2021-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多