cmdcommand-lineecho

Building arrays in command line and calling them in a for loop as a single command


I am trying to build two arrays (arr1 and arr2 which will have the same length) in the command line to be referenced in a for loop.

Building the command like this from the script,

set arr1[0]="a" & set arr1[1]="b" & set arr1[2]="c" & set arr1[3]="d" & set arr2[0]="e" & set arr2[1]="f" & set arr2[2]="g" & set arr2[3]="h" & for /L %G in (1,1,3) do echo %arr1[%G]% %arr2[%G]%

But this is not considering arr1 and arr2 as arrays but rather considering them as strings?

The output of the above command is as such Command line output

What am I missing? I have tried some of these variations but none seems to work for me:

I am sure its something very simple I am missing but can't seem to get my head around it.

NOTE: I do need all the commands to be as a single string for this command to be useful to me


Solution

  • echo %arr1[%G]% %arr2[%G]% is interpreted as (empty) variable echo %arr1[%, a string G[, another (empty) variable % %, the string arr2[, and a third (also empty) variable %G]%.

    The fact that empty variables don't show an empty string on the commandline (other than in a script) leads to an output that looks exactly like a repetition of the thing to be echoed (which I guess is the fact that confused you).

    Ok, now that we know, what happens and why - how to solve it?

    Well, you need another layer of variable expansion (the first one to expand %G, the second one to expand the variables built with %G (arr1[1] etc).
    The easiest way to achieve another layer of parsing is the call command:

    ...  do call echo %arr1[%G]% %arr2[%G]% 
    

    You can get a rough idea of what's going on here

    If you're into deep rabbit holes, get a big pot of coffee and read this (Be warned - it's heavy stuff. Prepare for brain meltdown)

    for "nice, undisturbed" output, suppress command repetition (after troubleshooting. Without @ you can actually watch the two stages of variable expansion):

    @(set arr1[0]="a" & set arr1[1]="b" & set arr1[2]="c" & set arr1[3]="d" & set arr2[0]="e" & set arr2[1]="f" & set arr2[2]="g" & set arr2[3]="h" & for /L %G in (1,1,3) do @call echo %arr1[%G]% %arr2[%G]%)