如何批量循环数组?

aur*_*rel 36 for-loop batch-file

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

set sources[0]="\\sources\folder1\"
set sources[1]="\\sources\folder2\"
set sources[2]="\\sources\folder3\"
set sources[3]="\\sources\folder4\"
Run Code Online (Sandbox Code Playgroud)

现在我想迭代这个数组:

for %%s in (%sources%) do echo %%s
Run Code Online (Sandbox Code Playgroud)

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

Dss*_*Dss 38

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

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
)
Run Code Online (Sandbox Code Playgroud)

一定要使用"call echo",因为echo不会有效,除非你有delayedexpansion并使用!代替 %%


Aac*_*ini 33

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

for /F "tokens=2 delims==" %%s in ('set sources[') do echo %%s
Run Code Online (Sandbox Code Playgroud)

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


LS_*_*ᴅᴇᴠ 24

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

for %%s in ("\\sources\folder1\" "\\sources\folder2\" "\\sources\folder3\" "\\sources\folder4\") do echo %%s
Run Code Online (Sandbox Code Playgroud)

  • 我只给了你这个建议,因为有时我会根据可能的解决方案重新考虑我的程序架构.想象一下,你创建数组只是为了能够遍历项目,然后在没有先前数组的情况下进行迭代将不再需要该数组! (21认同)
  • 这绝对没有帮助:/我问如何迭代数组,你给出了答案:"只是不要使用数组!" (10认同)

fox*_*ive 15

这是一种方式:

@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]%%
Run Code Online (Sandbox Code Playgroud)

  • @LS_dev哦,你们的小信仰.试试吧.:) (7认同)

Pat*_*zlo 5

我这样使用,重要的是变量只有 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
)
Run Code Online (Sandbox Code Playgroud)


Sve*_*son 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
)
Run Code Online (Sandbox Code Playgroud)

这实际上会产生以下错误的输出

donut
apple
banana
cherry
Run Code Online (Sandbox Code Playgroud)

首先打印最后一个元素。要解决此问题,更简单的方法是反转 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"
Run Code Online (Sandbox Code Playgroud)

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

apple
banana
cherry
donut
"Done"
Run Code Online (Sandbox Code Playgroud)