Page 1 of 1
Double expansion ? Trouble expanding a variable inside another variable and displaying it
Posted: 27 Jun 2018 18:07
by Osmium Programming
I was working on a command prompt in batch, and for the command that displays text on the screen, when I tried to display a variable it displayed it like this- %variable%
The relevant code for that is
If I enter %var% it displays %var%, not its contents (4).
However, when I change it to this, it works
Is there a way to still have user input for a, but output 4?
Re: Double expansion ? Trouble expanding a variable inside another variable and displaying it
Posted: 27 Jun 2018 19:26
by Grapefruits
This is coming from a total beginner in batch, but what I think you can do is put "call" before echo, to call the variable when its put out. Like this:
So it puts out
So that by putting in %var%, and calling echo a (which equals %var%) it'll expand it and print out 4. I remember reading about it somewhere on Stack Overflow, sorry I can't provide any links. Hope this helps...
Re: Double expansion ? Trouble expanding a variable inside another variable and displaying it
Posted: 28 Jun 2018 07:21
by aGerman
Um things like that are a little weird. As I understand your question you want the user to enter a variable name. Why?
Code: Select all
@echo off &setlocal
set var=4
set /p "a=Enter a variable name: "
echo Entered: %a%
:: assign the value of var to the entered name
set "%a%=%var%"
:: either use call ...
call echo %a%=%%%a%%%
:: ... or delayed expansion
setlocal EnableDelayedExpansion
echo %a%=!%a%!
endlocal
pause
Possible output:
Code: Select all
Enter a variable name: X
Entered: X
X=4
X=4
Drücken Sie eine beliebige Taste . . .
@Grapefruits
I'm afraid your code would only display 4 if the user entered 4 in the set /p statement.
Steffen
Re: Double expansion ? Trouble expanding a variable inside another variable and displaying it
Posted: 28 Jun 2018 08:53
by Grapefruits
@aGerman I thought OsmiumProgramming's question asked if entering a variable name with the percent signs around it in the set /p statement would expand to its contents. So if you enter %var% in the set /p statement, it would expand to its contents (so 4). If you enter %var% in set /p using my code it displays
not
.
Re: Double expansion ? Trouble expanding a variable inside another variable and displaying it
Posted: 28 Jun 2018 09:22
by aGerman
Also possible. Let's wait for a response
Steffen
Re: Double expansion ? Trouble expanding a variable inside another variable and displaying it
Posted: 02 Jul 2018 18:07
by Osmium Programming
That's not what I was looking for, but thanks anyway aGerman, it's nice to know there is always a person to ask. I appreciate it!
Also, thanks Grapefruits, that really helps!