I am using array in my for loop and trying to assign the value to a variable when each time loop process the array value. but when I am assigning the value to my variable, then the result is not as expected.

Here is what I am trying to do:

     @echo off
     setlocal enabledelayedexpansion
     SET var[0]=a
     SET var[1]=b
     SET var[2]=c
     SET var[3]=d
     for %%a in (0,1,2,3) do (
     SET name=%var[%%a]%
     ECHO %name%
     )

but the result is showing the last value of array which is 'd'. I don't want to use ECHO !name!. And expecting the output as below with %

 a
 b
 c
 d

1 Answers

1
an tran huu On Best Solutions

Normally it would shown ECHO is off. because %name% wasn't declared before. Let's say that you set the default value to null for %name%, then the output would be null instead of a, b, c and d. That's because %name% was declared outside the loop.

What is going on here? The echo %name% inside the code block will get the variable %name% first before run it, and therefore your code inside code block after parsed would be:

(
  set name=
  rem "%var[%" = "" and "%a]%" also = ""
  echo 
  rem %name% wasn't here, because it's parsed before you run it.
)

The ! symbol is the alternative variable pre/suffix, and only works if you use

setlocal EnableDelayedExpansion

Variable that's use ! will only get parsed when the statement is actually running instead of parsing:

(
  set name=!var[%%a]!
  echo !name!
)

This time, the code block would ignore the ! symbol and only looking for % symbol, and because the for loop, %%a will replace by a number:

(
  set name=!var[0]!
  echo !name!
)
(
  set name=!var[1]!
  echo !name!
)
(
  set name=!var[2]!
  echo !name!
)
(
  set name=!var[3]!
  echo !name!
)

Next time, if you want to change variable and use it, you might have to use ! instead of % otherwise you'll get repeated result. And if you want to echo the ! symbol, you can just escape it:

echo escaped "^!" symbol^!