1

I am following this tutorial on windows script arrays and for loops. The examples are not working, tested on both windows 7 and 10.

Batch script tutorial

When I run the following for loop:

:: @echo off 
set list = 1 2 3 4 
(for %%a in (%list%) do ( 
    echo %%a 
))

I get the following output:

set list = 1 2 3 4
(for %a in ((null)) do (echo %a  ) )

The content of the list varialble is not printed in the for loop. I was expecting to get

1
2
3
4

Any ideas?

4
  • Your variable was named list<space>. Change %list% to %list % Commented Jul 31, 2016 at 6:35
  • 4
    even better: get rid of the spaces around the =. They become part of the varaible name repectively the value. Commented Jul 31, 2016 at 6:45
  • Thanks, I knew it must be something simple. It is also wrong in the tutorial examples. Commented Jul 31, 2016 at 6:52
  • Yes, it is. Check out the batch page on the Documentation site, instead. Commented Jul 31, 2016 at 12:07

1 Answer 1

2

For info on using basic batch commands like SET, see SS64 great info source. In your case, as was commented above, the expanded variable name %list % must include space if present in its definition. If that space is not required in the variable definition, just remove it in the SET statement.

Spaces between array variable values list don't represent any problem, and can be quite handy in many example applications, in particular FOR loops, as they allow tokens use for finding the right values. This example works:

@echo off 
set "list= 1 2 3 4"
for %%a in (%list%) do ( 
    echo %%a 
)

For learning use of arrays in batch scripts, read Aacini's answers:

Using "array" terminology in batches is debated by some experts. See for example dbenham's answer in DIR output into BAT array?

Sign up to request clarification or add additional context in comments.

3 Comments

You fixed the problem in the code without explaining what the problem was, or how you fixed it. The rest of your answer obscures the issue.
Thanks. Added verbal explanation, though it was obvious from the script, which in many instances is the best and sufficient explanation "by example". Sorry, if I missed any of your contributions to the Array subject, pls add relevant links here or in the answer. :)
@Pohl7534 If the script works for you, consider upvoting AND accepting any answer in this thread by clicking "Arrow Up" and "Select" signs to the left of the answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.