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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With