Reputation: 355
I'm learning batch script in tutorialspoint now, here's a very simple script:
@echo off
set a[0]=0
set a[1]=1
set a[2]=2
set a[3]=3
set a[4]=4
set a[5]=5
for /l %%n in (0,1,5) do (echo %a[%%n]%)
why result is "ECHO is off"
if I write like for /l %%n in (0,1,5) do (echo a[%%n])
I can get
a[0]
a[1]
a[2]
a[3]
a[4]
a[5]
so why cannot I use echo to get the value of array?
Upvotes: 1
Views: 93
Reputation: 34989
Here is an alternative method without having to enable delayed expansion:
for /l %%n in (0,1,5) do (call echo %%a[%%n]%%)
The body of the loop call echo %%a[%%n]%%
is parsed two times due to call
; during the first time it becomes call echo %a[0]%
, supposing the current value of %%n
is 0
, because %%
becomes %
, and during the second time, %a[0]%
is replaced by the respective value of the variable.
In your approach, echo %a[%%n]%
, the command line interpreter sees two variables to expand, namely %a[%
and %n]%
, which are both undefined and become therefore replaced by nothing.
Upvotes: 1
Reputation: 82438
As you shouldn't use percent expansion in a block (here it's a FOR-block), as percents are expanded while the block is parsed.
Use delayed expansion instead.
setlocal EnableDelayedExpansion
for /l %%n in (0,1,5) do (echo !a[%%n]!)
Upvotes: 1