Echo batch file arrays using a variable for the index?

天大地大妈咪最大 提交于 2020-01-10 05:15:06

问题


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


回答1:


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




回答2:


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.




回答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



来源:https://stackoverflow.com/questions/20385885/echo-batch-file-arrays-using-a-variable-for-the-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!