How to use variables in variables? This code:
set newvar=%var%var2%%
doesn't work. So, what to do? I can't write my program without it.
How to use variables in variables? This code:
set newvar=%var%var2%%
doesn't work. So, what to do? I can't write my program without it.
A relatively slow method. The CALL command provides an extra level of variable expansion. The percents around the outer variable name are doubled to delay the expansion until after the inner variable has been expanded.
@echo off
setlocal
set "var1=value"
set "var2=1"
call set "newvar=%%var%var2%%%"
A much better method is to use delayed expansion. It must be first enabled with SETLOCAL ENABLEDELAYEDEXPANSION. The variable within percents is expanded when the line is parsed. The variable within exclamation points is expanded after parsing, just before the line is executed.
@echo off
setlocal enableDelayedExpansion
set "var1=value"
set "var2=1"
set "newvar=!var%var2%!"
Generally, I'd try to avoid scenarios like this. While it is possible, it is far from performant and not very easy to read either - basically you'd have to parse the output of the set command.
set index=9
set var9=Goal
echo %var9%
for /F "usebackq tokens=1* delims==" %I in (`set`) do if "%I" == "var%index%" set result=%J
echo %result%
I agree with AFH; you need to get CMD to “double-parse” the set statement.
But I’ve found a kludge for doing it that doesn’t involve a temporary batch file
(or looking at every variable to find the one you want).
It uses a subroutine and a trick called delayed variable expansion.
Enable delayed expansion by adding
setlocal enabledelayedexpansion
somewhere near the beginning of your batch file.
The purpose of delayed variable expansion is somewhat complicated –
see SET /? and SETLOCAL /? for more information –
but the important thing to know is that it lets you reference variables
with !variable_name! in addition to %variable_name%.
So here we go:
@echo off
setlocal enabledelayedexpansion
set var1=red
set var2=orange
set var3=yellow
set A=2
call :kludge var%A%
echo Newvar is %newvar%.
goto :eof
:kludge
set newvar=!%1!
exit /b
When we jump to :kludge, the statement is first transformed into set newvar=!var2!
(because %1, the first argument to the subroutine, is var2)
and then set newvar=orange (just as if the statement had been set newvar=%var2%).
So newvar gets set to orange.
BTW, goto :eof and exit /b are interchangeable.
If called from within a subroutine (i.e., someplace you got to with a call statement),
they cause a return to the caller.
Otherwise, they act like a jump to the end of the batch file, causing the batch job
to terminate without blowing away the parent, interactive, Command Prompt.