如何批量循环数组?

时间:2013-08-27 09:49:17

标签: for-loop batch-file

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

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

它不起作用!似乎脚本不会进入循环。这是为什么?我怎么能迭代呢?

6 个答案:

答案 0 :(得分:32)

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

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"因为回声不会起作用,除非你有delayedexpansion和使用!而不是%%

答案 1 :(得分:30)

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

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

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

答案 2 :(得分:20)

如果您不需要环境变量,请执行以下操作:

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

答案 3 :(得分:14)

这是一种方式:

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

答案 4 :(得分:3)

对于后代:我只是想对@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"

答案 5 :(得分:1)

我这样使用,重要的是该变量只有1个长度,例如%% a,而不是%% repo:

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
)