1

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?

JiangFeng
  • 355
  • 2
  • 14
  • 1
    When the command processor finds a block (anything between parentheses), parses it completely and expand variables to the value they have when the block is evaluated. If you update a variable value within a block, you need to enable delayed expansion for the variable to reflect changes made. Use `setlocal EnableDelayedExpansion` and change syntax from `%var%` to `!var!` to make delayed expansion works. – elzooilogico Jan 03 '17 at 12:28
  • 1
    There's a nice explanation on [How does the Windows Command Interpreter (CMD.EXE) parse scripts?](http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/4095133#4095133) – elzooilogico Jan 03 '17 at 12:28
  • Interesting site at the given link. Pretty presentation, lot of descriptions and code, but all the examples _are wrong_! There must not be spaces before the equal sign in `set` commands. You may review a detailed description on array management in Batch files at [this answer](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990). – Aacini Jan 03 '17 at 15:53

2 Answers2

1

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]!)
jeb
  • 78,592
  • 17
  • 171
  • 225
1

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.

aschipfl
  • 33,626
  • 12
  • 54
  • 99