Kunal
Kunal

Reputation: 76

How to use variable inside For /L Loop IN List ( Batch File Programming)

I want to place a variable value in for loop IN list. the myvariable is obtained from the user input.

Example:

for /L %%G IN (1 1 %myvariable%) DO command

If i use this syntax, the loop is never executed. Is it possible to assign IN list to for loop at runtime ?

Please help me out.

Upvotes: 1

Views: 11538

Answers (2)

dbenham
dbenham

Reputation: 130819

Mark has identified a missing space between IN and (, but can't tell if that is your actual code or just a typo when you created the question.

Another possibility is that your variable is being set within the same code that later expands the value. The following code will fail:

(
  set /p "myvariable=Enter a value: "
  echo myvariable=%myvariable%
)

The reason the above fails is that the % expansion occurs when the statement is parsed, and the entire block within the parentheses is treated as a single statement. So it expands to the value that existed prior to executing the SET /P.

If you want the value that exists at run time, then you need to use delayed expansion

setlocal enableDelayedExpansion
(
  set /p "myvariable=Enter a value: "
  echo myvariable=!myvariable!
)

This type of problem frequently occurs with IF and FOR commands. I can't tell if this is your problem because you haven't provided enough context.

Upvotes: 2

Mark
Mark

Reputation: 3690

Your idea is right, but your syntax is wrong. It should be:

for /l %%G in (1, 1, %myvariable%) do command

Upvotes: 4

Related Questions