简体   繁体   English

用于循环变量扩展的Windows批处理脚本不起作用

[英]windows batch script for loop variable expansion not working

I am following this tutorial on windows script arrays and for loops. 我正在Windows脚本数组和for循环上关注本教程。 The examples are not working, tested on both windows 7 and 10. 这些示例无法正常运行,在Windows 7和10上均进行了测试。

Batch script tutorial 批处理脚本教程

When I run the following for loop: 当我运行以下for循环时:

:: @echo off 
set list = 1 2 3 4 
(for %%a in (%list%) do ( 
    echo %%a 
))

I get the following output: 我得到以下输出:

set list = 1 2 3 4
(for %a in ((null)) do (echo %a  ) )

The content of the list varialble is not printed in the for loop. 变量列表的内容未打印在for循环中。 I was expecting to get 我期待得到

1
2
3
4

Any ideas? 有任何想法吗?

For info on using basic batch commands like SET, see SS64 great info source. 有关使用基本批处理命令(如SET)的信息,请参阅SS64很好的信息源。 In your case, as was commented above, the expanded variable name %list % must include space if present in its definition. 在您的情况下,如前所述,扩展变量名称%list%如果在其定义中存在空格,则必须包含空格。 If that space is not required in the variable definition, just remove it in the SET statement. 如果变量定义中不需要该空间,则只需在SET语句中将其删除。

Spaces between array variable values list don't represent any problem, and can be quite handy in many example applications, in particular FOR loops, as they allow tokens use for finding the right values. 数组变量列表之间的空格不代表任何问题,并且在许多示例应用程序中特别方便,尤其是FOR循环,因为它们允许使用令牌来查找正确的值。 This example works: 此示例有效:

@echo off 
set "list= 1 2 3 4"
for %%a in (%list%) do ( 
    echo %%a 
)

For learning use of arrays in batch scripts, read Aacini 's answers: 要了解在批处理脚本中使用数组的方法,请阅读Aacini的答案:

Using "array" terminology in batches is debated by some experts. 一些专家对批量使用“数组”术语进行了辩论。 See for example dbenham 's answer in DIR output into BAT array? 例如在DIR输出到BAT阵列中查看dbenham的答案吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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