User inputs a variable which is stored within a variable

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
maniacal
Posts: 15
Joined: 29 Nov 2010 23:02

User inputs a variable which is stored within a variable

#1 Post by maniacal » 29 Nov 2010 23:45

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?

orange_batch
Expert
Posts: 442
Joined: 01 Aug 2010 17:13
Location: Canadian Pacific
Contact:

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

#2 Post by orange_batch » 30 Nov 2010 00:42

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.

maniacal
Posts: 15
Joined: 29 Nov 2010 23:02

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

#3 Post by maniacal » 30 Nov 2010 00:49

Works perfect, can't believe I overlooked that use of call....

Post Reply