Batch file - variables in variables

I used a for loop to split the string with spaces. I also used a loop for each word in my variable such as var1 = this, var2 = is, var3 = a, var4 = test. It looks like this: "set var! Count! = %% A"

It works. I just need to remember this. How should I do it? Logically, I think it will look like this:% Var% Amount %%

Can someone explain to me how to get this? If I have "count" 1, what should I do to get "var1"?

+3


source to share


3 answers


There is an easy way, you need to enable slow expansion, so first place setlocal enabledelayedexpansion

and then use exclamation marks to access these variables. Your script should look like this:



@echo off
setlocal enabledelayedexpansion
:: Here comes your loops to set the variables
echo/!var%count%!

      

+2


source


When moving arrays in batch use for /l

:

@echo off
setlocal enabledelayedexpansion
var0 = A
var1 = B
var2 = C
var3 = D
var4 = E

for /l %%a in (0, 1, 4) do (
Echo var%%a = !var%%a!
)

      



Output:

var0 = A
var1 = B
var2 = C
var3 = D
var4 = E

      

0


source


If you want to print the contents of var1 outside of the for statement use

  Echo %var1%

      

To first print the contents of var1 inside a block, you need to enable slow expansion and instead of including variable references with percent signs, you use

   Echo !var1!

      

-1


source







All Articles