Wednesday, 25 April 2018

Batch file. Variable in variable


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.



Answer



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.


No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...