Home > database >  How can I use a string variable in .bat for-loop?
How can I use a string variable in .bat for-loop?

Time:12-18

In a .bat file, it's ok to use a char-type variable in for-loop. The code below, for example,

@echo off
for /l %%p in (15,2,20) do (
    echo %%p
)

gives "15 17 19", as expected. But it doesn't work anymore if I use a string-type variable,

@echo off
for /l %%parameter in (15,2,20) do (
    echo %%parameter
)

I wonder if it's possible to make the 2nd piece of code work. Can somebody help me out? Many thanks.

CodePudding user response:

you can use an ordinary environment variable defined with a for metavariable in place of the for metavariable:

@Echo off

 Set "Loop[1]=%%#"
 Set "Loop[2]=%%@"

 For /l %Loop[1]% in (1 1 5) Do For /l %Loop[2]% in (5 1 9) Do (
  <nul set /p=%Loop[1]%   %Loop[2]%=
  Cmd /c Set /A %Loop[1]%   %Loop[2]%
  Echo(
 )

CodePudding user response:

The use of %value% is used to define variables that contain more than one character. The %% is used to define variables consisting of a single character.

Since only %% is allowed in the for loop, %value% cannot be used to define variables with more than one character. In this case, the only option is to define a single character variable using %%; such as %%p.

The syntax for the for loop is available below:

for %%a in (list) do command [ parameters ]
  • Related