[英]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?正如您在 echo 中看到的那样,我想获取变量 1 的值,即
test1
等等……有什么解决方法吗? 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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.