Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put variable value inside another variable name in batch?

Tags:

batch-file

Suppose that I have defined the following variables in a batch script:

set VariableFirst=value1
set VariableLast=value2

Then I set another variable in another portion of the code

set Type=First

and I wanna access one among %VariableFirst% and %VariableLast% depending on the value of variable %Type% (Something like echo %Variable%Type%% but this doesn't work). How can I do that in a Windows batch script?

like image 684
Bruno Caetano Avatar asked Feb 11 '23 10:02

Bruno Caetano


1 Answers

In your specific case this should work:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
set VariableFirst=value1
set VariableLast=value2
set Type=First
echo !Variable%Type%!

Here is the explanation:

The key is SETLOCAL EnableDelayedExpansion. Usually your variables are evaluated at parse time. Consider this code:

@ECHO OFF
SET a=b
SET b=abc
ECHO %%a%%

You want %a% to be evaluated to K so ECHO %%a%% would turn ECHO %b% and the output would be abc. But this won't work this way. Evaluation at parse time means that the values of the variables are set without processing the code. SET a=b and SET b=abc will work but ECHO %%a%% wont because to know that %a% is b the first line has to be executed but the execution happens after the variables are set. So %%a%% bevomes %a% and the output is just %a%.

What you need to do is to force the interpreter to evaluate the last line at run time means execute line by line and evaluate the last line as you reach it. To do so you need to add SETLOCAL EnableDelayedExpansion at the beginning of your script. Now !...! forces the interpreter to evaluate the current value of the variable surrounded by the exclamation marks considering all changes which were made to variables before this line.

Now take a look at this:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET a=b
SET b=abc
ECHO !%a%!

Now a is b, b is abc and !%a%! is evaluated at run time. So in this case ECHO !%a%! is evaluated at a point where the console knows that %a% is b and can replace !%a%! with !b! which is abc. So the output is abc.

like image 165
MichaelS Avatar answered Apr 27 '23 16:04

MichaelS