1

This question is similar to that of Echo batch file arrays using a variable for the index? but it doesn't answer my question.

I have a batch file that contains a list. I am iterating through a for loop and want to print out an element from the list with each iteration using the iteration number (i.e. list[i])

I am using SETLOCAL enableextensions enabledelayedexpansion

and I've tried using:

!list[%i%]!
%list[%i%]%
!list[!i!]!

I'm aware I could use FOR /L but this would not work in the context I want to use this.

Here's the code I'm currently using

SETLOCAL enableextensions enabledelayedexpansion
SET list[0]=1
SET list[1]=2
SET list[2]=3
SET list[3]=4
SET list[4]=5
SET /a i=0
FOR /L %%G IN (1,1,5) DO (
    echo list[!i!] = %list[!i!]%
    SET /a i+=1
)

Expected:

list[0] = 1
list[1] = 2
list[2] = 3
list[3] = 4
list[4] = 5

Actual:

list[0] = 
list[1] = 
list[2] = 
list[3] = 
list[4] =
Compo
  • 36,585
  • 5
  • 27
  • 39
jamesD
  • 55
  • 6
  • 1
    `echo !list[%%G]!` - you don't need `i` (as `%%G` is your iterator). Also you probably want `FOR /L %%G IN (0,1,4)` – Stephan May 21 '19 at 16:57
  • Or do a simple `set list[` this has the disadvantage that it is alpha sorted, i.e. 1,10,11,2 etc. –  May 21 '19 at 17:00
  • In case you can't use `for /l` you might use double delayed expansion with a pseudo call and doubled percent signs: `call echo list[!i!] = %%list[!i!]%%` –  May 21 '19 at 17:04
  • 1
    Was going to answer, but it got closed before I hit submit.. anyway. not sure why you needed to set a counter for a counter, `set /a i` is not needed. just do `FOR /L %%G IN (0,1,4) DO (echo list[%%G] = !list[%%G]!)` – Gerhard May 21 '19 at 17:20
  • Thanks for all the sugegstions, the answer is explained in great detail in the link this has been marked a duplicate of. For my particular issue, the best answer is from @LotPings using %% around the list[] variable. – jamesD May 21 '19 at 17:37

0 Answers0