Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo batch file arrays using a variable for the index?

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

like image 362
Dss Avatar asked Dec 04 '13 21:12

Dss


People also ask

How do I echo a variable in a batch file?

Please open a command prompt window, run set /? and read the output help. The syntax is set /P variable=prompt text or better set /P "password=Enter your password: " . And please note that variable password keeps its current value if already defined and user hits just RETURN or ENTER.

How to use array in batch script?

Arrays are not specifically defined as a type in Batch Script but can be implemented. The following things need to be noted when arrays are implemented in Batch Script. Each element of the array needs to be defined with the set command. The 'for' loop would be required to iterate through the values of the array.

How do you loop a batch file?

Pressing "y" would use the goto command and go back to start and rerun the batch file. Pressing any other key would exit the batch file.


3 Answers

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

like image 102
npocmaka Avatar answered Nov 16 '22 00:11

npocmaka


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.

like image 20
Mad Physicist Avatar answered Nov 16 '22 01:11

Mad Physicist


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

like image 42
Tyler Silva Avatar answered Nov 16 '22 00:11

Tyler Silva