- 1 year ago
Expand variable in a batch file For loop
To expand a variable in a FOR
loop in a batch file, you can use the SETLOCAL ENABLEDELAYEDEXPANSION
command to enable delayed expansion of variables. Here's an example code snippet:
batch@echo off
setlocal enabledelayedexpansion
set myvar=hello
for %%i in (1 2 3) do (
echo Iteration %%i: !myvar!
set myvar=world
)
In this example, we first set the variable myvar
to the value "hello". We then use a FOR
loop to iterate over the values 1, 2, and 3. Inside the loop, we use the echo
command to display the current iteration number and the value of the myvar
variable, using the syntax !myvar!
to expand the variable inside the loop.
Note that we also use the SETLOCAL ENABLEDELAYEDEXPANSION
command before the FOR
loop to enable delayed expansion of variables. This allows us to expand the myvar
variable inside the loop using the !
syntax.
Without delayed expansion, the FOR
loop would expand the variable to its initial value of "hello" for each iteration, regardless of any changes made to the variable inside the loop. With delayed expansion, the variable is expanded at the time of execution, allowing us to see the changes made to the variable inside the loop.