- 1 year ago
Windows command batch file calling variable from string in nested loop
To access variables from a string in a nested loop in a Windows command batch file, you can use delayed expansion and the !
syntax. Here's an example:
batch@echo off
setlocal enabledelayedexpansion
rem Outer loop
for %%x in (A B C) do (
set outerVar=OuterVariableValue_%%x
rem Inner loop
for %%y in (1 2 3) do (
set innerVar=!outerVar!_InnerVariableValue_%%y
echo !innerVar!
)
)
endlocal
In this example, the outer loop iterates over the values A, B, and C, and the inner loop iterates over the values 1, 2, and 3. Within the nested loops, we create variables outerVar
and innerVar
.
To access the outerVar
variable within the inner loop, we use delayed expansion and the !
syntax (!outerVar!
). This allows the value of outerVar
to be evaluated dynamically at runtime, considering the current iteration of the outer loop.
The !
syntax is used to expand the variable when delayed expansion is enabled (setlocal enabledelayedexpansion
). The echo !innerVar!
statement in the inner loop demonstrates the usage of the expanded variable.
By enabling delayed expansion and using the !
syntax, you can access variables from a string in a nested loop within a Windows command batch file.