BBMAN225
BBMAN225

Reputation: 673

Why won't this batch code work?

Assuming that %Edata% was a variable written like this "A;B;C;1;2;3;" then this code should be able to separate it into a bunch of numbered variables:

set /a c=0
FOR %%A IN (%Edata%) DO (
  set /a c=%c%+1
  set var%c%=%%A
  echo.^>^>^> Set "%%A" to "var%c%"
)

Only the result is setting all parts of the variable to var0 because the %c% variable doesn't count up each time like it's supposed to. Could someone explain why?

Upvotes: 1

Views: 103

Answers (1)

fthiella
fthiella

Reputation: 49089

This code works:

@echo off
setlocal EnableDelayedExpansion

set /a c=0
FOR %%A IN (%Edata%) DO (
  set /a c=!c!+1
  set var!c!=%%A
  echo.^>^>^> Set "%%A" to "var!c!"
)

The problem in your script is that variables by default are expanded at parse time and not at execution time. In this case c is expanded only once, before entering the loop, that's why its value is always 0 and it never changes.

You have to enable the expansion of variables at execution time with this command:

setlocal EnableDelayedExpansion

and you have to use !c! instead of %c% inside the for loop.

Upvotes: 2

Related Questions