Taking input and storing an a variable

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
MLGsuperGame414
Posts: 54
Joined: 10 Nov 2011 20:40

Taking input and storing an a variable

#1 Post by MLGsuperGame414 » 14 Jul 2013 11:55

I'm not sure even where to start, I would like to know how to store given info into a variable.

For example the user is prompted to give an input of either one or two and its then stored in a variable that can later be used, also in C++ variables can be local or global depending on where you're going to use them. Is it the same in batch?

penpen
Expert
Posts: 2009
Joined: 23 Jun 2013 06:15
Location: Germany

Re: Taking input and storing an a variable

#2 Post by penpen » 14 Jul 2013 12:33

First:
MLGsuperGame414 wrote:I'm not sure even where to start, I would like to know how to store given info into a variable

Code: Select all

set "variable=given info"
Second:
MLGsuperGame414 wrote:For example the user is prompted to give an input of either one or two and its then stored in a variable that can later be used

Code: Select all

set "variable that can later be used="
set /p "variable that can later be used=give an input of either one or two "
echo variable that can later be used=%variable that can later be used%
Third:
MLGsuperGame414 wrote:also in C++ variables can be local or global depending on where you're going to use them. Is it the same in batch?
Yes:

Code: Select all

:: test.bat
setlocal
set "TEST=outer local"
setlocal
set "TEST=inner local"
echo TEST=%TEST%
endlocal
echo TEST=%TEST%
endlocal
echo TEST=%TEST%
goto :eof


penpen

MLGsuperGame414
Posts: 54
Joined: 10 Nov 2011 20:40

Re: Taking input and storing an a variable

#3 Post by MLGsuperGame414 » 14 Jul 2013 12:55

So

Code: Select all

setlocal
set "Test=outer local"


does what compared to

Code: Select all

setlocal
set "Test=outer inner"


Is outer global?

penpen
Expert
Posts: 2009
Joined: 23 Jun 2013 06:15
Location: Germany

Re: Taking input and storing an a variable

#4 Post by penpen » 14 Jul 2013 14:14

The command setlocal does the following:
help setlocal wrote:Starts localization of environment variables in a batch file. Localization continues until a matching endlocal command is encountered or the end of the batch file is reached [...]

So you may change variables within an setlocal-endlocal block as you want, but if the program has left this block (after the endlocal command of this block) all changes within the block are gone.

Run the example (test.bat) and you will see it.

penpen

Edit: Global variables cannot be changed in a cmd shell using the set command.
The best you can do is that changes are durable within the shell session.
This can be achieved in a batch program before the first setlocal and after the endlocal of this block.

Post Reply