如何批量循环数组?

问题描述 投票:0回答:6

我创建了一个像这样的数组:

set sources[0]="\\sources\folder1\"
set sources[1]="\\sources\folder2\"
set sources[2]="\\sources\folder3\"
set sources[3]="\\sources\folder4\"

现在我想迭代这个数组:

for %%s in (%sources%) do echo %%s

这不起作用!看来脚本没有进入循环。这是为什么?那我该如何迭代呢?

for-loop batch-file
6个回答
57
投票

使用定义和不需要延迟扩展的循环的另一种选择:

set Arr[0]=apple
set Arr[1]=banana
set Arr[2]=cherry
set Arr[3]=donut

set "x=0"

:SymLoop
if defined Arr[%x%] (
    call echo %%Arr[%x%]%%
    set /a "x+=1"
    GOTO :SymLoop
)

请确保使用“call echo”,因为除非您延迟扩展并使用,否则 echo 将无法工作!而不是%%


42
投票

如果你不知道数组有多少个元素(似乎是这样),你可以使用这个方法:

for /F "tokens=2 delims==" %%s in ('set sources[') do echo %%s

请注意,元素将按“字母顺序”处理,也就是说,如果元素超过 9 个(或 99 个等),则索引必须在元素 1..9(或 1..9)中留零。 .99等)


31
投票

for %%s in ("\\sources\folder1\" "\\sources\folder2\" "\\sources\folder3\" "\\sources\folder4\") do echo %%s



18
投票

@echo off set sources[0]="\\sources\folder1\" set sources[1]="\\sources\folder2\" set sources[2]="\\sources\folder3\" set sources[3]="\\sources\folder4\" for /L %%a in (0,1,3) do call echo %%sources[%%a]%%



5
投票

for %%r in ("https://github.com/patrikx3/gitlist" "https://github.com/patrikx3/gitter" "https://github.com/patrikx3/corifeus" "https://github.com/patrikx3/corifeus-builder" "https://github.com/patrikx3/gitlist-workspace" "https://github.com/patrikx3/onenote" "https://github.com/patrikx3/resume-web") do ( echo %%r git clone --bare %%r )



5
投票
对于子孙后代

:我只是想对@dss提出一个小小的修改,否则答案很好。 在当前结构中,当您将 Arr 中的值分配给循环内的临时变量时,完成 DEFINED 检查的方式会导致意外输出:

示例:

@echo off set Arr[0]=apple set Arr[1]=banana set Arr[2]=cherry set Arr[3]=donut set "x=0" :SymLoop if defined Arr[%x%] ( call set VAL=%%Arr[%x%]%% echo %VAL% REM do stuff with VAL set /a "x+=1" GOTO :SymLoop )

这实际上会产生以下
不正确

输出 donut apple banana cherry

首先打印最后一个元素。
要解决此问题,更简单的方法是反转 DEFINED 检查,使其在完成数组时跳过循环,而不是执行它。像这样:

@echo off set Arr[0]=apple set Arr[1]=banana set Arr[2]=cherry set Arr[3]=donut set "x=0" :SymLoop if not defined Arr[%x%] goto :endLoop call set VAL=echo %%Arr[%x%]%% echo %VAL% REM do your stuff VAL SET /a "x+=1" GOTO :SymLoop :endLoop echo "Done"

无论您在 SymLoop 内做什么,总会产生所需的 
正确

输出 apple banana cherry donut "Done"

© www.soinside.com 2019 - 2024. All rights reserved.