Page 1 of 1

User inputs a variable which is stored within a variable

Posted: 29 Nov 2010 23:45
by maniacal
I recently experienced a problem with the 'set /p variable=' command.

Here is the problem code

Code: Select all

@echo off
:begin
set /p input=Input:
%input%
goto begin


The intention of this was so that whatever the user inputs will be passed as the next line of code, like the CMD box does.

The problem I experienced was that when a user inputs a variable, the variable name is outputted rather than the variable content
Eg. when the user inputs 'echo %cd% the output is:

Input:echo %cd%
%cd%

%cd% is outputted rather than the actual content of that variable which, in this example, would be the current directory, or C:\Users\Sean\Desktop.

I have come up with a somewhat inefficient way around this problem:

Code: Select all

@echo off
:begin
set /p input=Input:
echo %input% >temp.bat
call temp.bat
del temp.bat
goto begin


As you can see, the variable is inputted into a batch file (echo %input% >temp.bat), this file is then called (call temp.bat) and then deleted (del temp.bat).
This does solve the problem but it seems like there should be a much simpler and elegant solution to this problem.
Any suggestions?

Re: User inputs a variable which is stored within a variable

Posted: 30 Nov 2010 00:42
by orange_batch
This happens because:

1. set /p automatically escapes all input from the user.

2. Command Prompt only runs each code block through one interpreter phase, so only the content of %input% is expanded.

My solution:

Code: Select all

set "var=Hello World"
set /p "input=Command: "
call %input%

Seems to work fine.

Re: User inputs a variable which is stored within a variable

Posted: 30 Nov 2010 00:49
by maniacal
Works perfect, can't believe I overlooked that use of call....