You are not logged in.

#1 07 Sep 2020 02:41

eldiener
New Member
Registered: 07 Sep 2020
Posts: 2

Use value of environment variable as environment variable

Let us suppose I have in a batch file, try_test.bat:

SET XXX_NAME=a b c
SET XXX_ADDRESS=d e f

Now the user passes in either the variable NAME or ADDRESS aand I want to get the expansion.
I try:

SET SOME_VARIABLE=XXX_%1

but now I can not seem to figure out how I can expand SOME_VARIABLE to get either 'a b c' or 'd e f' ? Let us suppose the user invokes:

try_test NAME

If I try in the batch file:

@echo %SOME_VARIABLE%

I just get back:

XXX_NAME

where I want to reference the value of the XXX_NAME environment variable, which is 'a b c'.

I know there must be some way to do this but I can not figure it out ? Does anybody know how ?

Offline

#2 07 Sep 2020 03:20

Shadow Thief
Member
Registered: 12 Jul 2012
Posts: 205

Re: Use value of environment variable as environment variable

If you want to build a variable using another variable as its name, you have two options:

Either use call and a set of double percents for the outer variable

call echo %%%SOME_VARIABLE%%%

Or use delayed expansion and exclamation points for the outer variable

setlocal enabledelayedexpansion
echo !%SOME_VARIABLE%!

Offline

#3 07 Sep 2020 05:27

eldiener
New Member
Registered: 07 Sep 2020
Posts: 2

Re: Use value of environment variable as environment variable

Shadow Thief wrote:

If you want to build a variable using another variable as its name, you have two options:

Either use call and a set of double percents for the outer variable

call echo %%%SOME_VARIABLE%%%

Or use delayed expansion and exclamation points for the outer variable

setlocal enabledelayedexpansion
echo !%SOME_VARIABLE%!

Thank you ! The first solution is truly arcane, but the second is very understandable.

Offline

#4 07 Sep 2020 14:51

bluesxman
Member
From: UK
Registered: 29 Dec 2006
Posts: 1,129

Re: Use value of environment variable as environment variable

The first one just needs a little explanation.  Consider:

SOME_VARIABLE=OTHER_VARIABLE
OTHER_VARIABLE=something
call echo %%%SOME_VARIABLE%%%

Using "call" causes the string to be evaluated twice.  First time round, the "%SOME_VARIABLE%" is expanded to "OTHER_VARIABLE" and instances of "%%" are reduced to "%".  Thus the "echo" receives "%OTHER_VARIABLE%" and you see "something".

Last edited by bluesxman (07 Sep 2020 14:52)


cmd | *sh | ruby | chef

Offline

#5 15 Oct 2020 15:18

tra
Member
From: Andorra
Registered: 15 Oct 2020
Posts: 6

Re: Use value of environment variable as environment variable

another way is for command

for %%a in ("environment var") do echo !%%~a!

with extensions enabled


cmd|ps|rexx|ada|C|C++|C#|vba|java|js|rpg|cobol|mih|perl|al

Offline

Board footer

Powered by