Windows Batch Variable within variable

12,903

Solution 1

Your example in your question is a mess, but I think I understand what you are looking for:

@echo off
setlocal

set C1=apple
set C2=orange
set C3=banana

set num=2


:: Inefficient way without delayed expansion
:: This will be noticeably slow if used in a tight loop with many iterations
call echo %%C%num%%%

:: The remaining methods require delayed expansion
setlocal enableDelayedExpansion

:: Efficient way 1
echo(
echo !C%num%!

:: Efficient way 2 - useful if inside parenthesized block
:: where %num% will not give current value
echo(
for %%N in (!num!) do echo !C%%N!

:: Showing all values via a loop
echo(
for /l %%N in (1 1 3) do echo !C%%N!

Solution 2

You may be looking for the Call Set command. This sets cnum to string c1, c2, c3 etc. It changes each time %num% changes. You can then use Call Set to assign any variable (h1 for example) to the value of the variable cnum stands for.

@echo off
setlocal enabledelayedexpansion
    set c5=test
    set num=5

    :: set cnum to string "c5"
        set cnum=c%num%
    :: set h1 to to the existing variable c5 
        call set "h1=%%%cnum%%%"
        echo %h1%

Solution 3

Are you after something like this?

cls
@echo off
setlocal EnableDelayedExpansion
Set num=5
Set "c!num!=test"
Echo !c5!

See http://ss64.com/nt/delayedexpansion.html for more info on delayed expansion.

cls
@echo off
setlocal EnableDelayedExpansion
set num=4
set c1=this is a demo
set c2=second example
set c3=third
set c4=this is the one I want
set c5=last
Echo !c%num%!
Share:
12,903
Strictly No Lollygagging
Author by

Strictly No Lollygagging

Updated on June 14, 2022

Comments

  • Strictly No Lollygagging
    Strictly No Lollygagging almost 2 years

    In windows batch could you set a variable within a variable?

    Explained:

    So the %num% is within the variable.

    set num=5
    set cnum=test
    set h1=%c%num%%
    

    Is it possible to make the percents work like parenthesis? The output should be h1=test

    Any help would be appreciated.

  • Strictly No Lollygagging
    Strictly No Lollygagging over 9 years
    Sort of, It's like that only reversed. I'm trying to avoid having to script a lot more than I need to and call a predefined variable that varies according to certain conditions, example:
  • Strictly No Lollygagging
    Strictly No Lollygagging over 9 years
    set value=%start%number%% where the %number% can be changed.
  • Strictly No Lollygagging
    Strictly No Lollygagging over 9 years
    start1, start2, start3 etc. are already defined variables, I just need to load certain variables according to the %number% variable.
  • Strictly No Lollygagging
    Strictly No Lollygagging over 9 years
    Thanks so much! This is exactly what I needed.