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 t
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.
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
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