11

If I have a batch file and I am setting arrays with an index that is a variable

@echo off
SET x=1
SET myVar[%x%]=happy

How do I echo that to get "happy" ?

I've tried

ECHO %myVar[%x%]%
ECHO %%myVar[%x%]%%
ECHO myVar[%x%]

But none of them work.

It works fine if I use the actual number for the index

ECHO %myVar[1]%

But not if the index number is also a variable

Dss
  • 2,162
  • 1
  • 24
  • 27
  • 3
    I suggest you to review: [arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Dec 05 '13 at 01:02

3 Answers3

12
SET x=1
SET myVar[%x%]=happy

call echo %%myvar[%x%]%%
set myvar[%x%]
for /f "tokens=2* delims==" %%v in ('set myvar[%x%]')  do @echo %%v
setlocal enableDelayedExpansion
echo !myvar[%x%]!
endlocal

I would recommend you to use

setlocal enableDelayedExpansion
echo !myvar[%x%]!
endlocal

as it is a best performing way

npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • 1
    Yes of course... and I even did that in another section of my code, but didn't put 2 and 2 together. Thanks! – Dss Dec 04 '13 at 21:34
6

There is a special ! character in batch to deal with your situation. Use echo !myVar[%x%]!, from How to return an element of an array in Batch?. ! means delayed expansion. The variable myVar will not get expanded until after %x% is, yielding the expression you want.

Community
  • 1
  • 1
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
3

one way you can do this is to use

call echo %%myVar[%x%]%%

call lets you put variables in places where they wouldn't normally work, if you use the double percents

Tyler Silva
  • 411
  • 6
  • 14