How to input a string from user into environment variable from batch file
Asked Answered
S

3

46

I want to prompt the user for some input detail, and then use it later as a command line argument.

Syllabi answered 4/10, 2009 at 8:55 Comment(0)
S
75

You can use set with the /p argument:

SET /P variable=[promptString]

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

So, simply use something like

set /p Input=Enter some text: 

Later you can use that variable as argument to a command:

myCommand %Input%

Be careful though, that if your input might contain spaces it's probably a good idea to quote it:

myCommand "%Input%"
Scape answered 4/10, 2009 at 9:5 Comment(4)
Is something like that for input password ?Cichlid
There are numerous answers to this, usually via a VBScript to get the password without echoing to the console.Scape
I used this to ask for input file path to give to an EXE, but if that PATH also contains an environment variable ("%MY_SRC_DIR%\blabla\file.ext") it doesn't work, I have to give it the absolute or relative file path without the environment variable. Any way to fix this?Kanara
@dominicbri7: You'd need to expand the environment variable, that is, make it visible twice to the cmd parser. call set Input=%Input% would be a way. This would be parsed twice (due to the call), expanding %Input% the first time and whatever environment variables you have in there the second time. But this doesn't really have anything to do with this question or answer.Scape
S
2

A rather roundabout way, just for completeness:

 for /f "delims=" %i in ('type CON') do set inp=%i

Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.

Syllabi answered 4/10, 2009 at 9:8 Comment(1)
That one is ... interesting. Now you only need to educate the user that only her last line entered will be used :-)Scape
K
0

Thanks! I just wanted this to keep my bat file from Closing:

set /p anykey=Press any key to continue

Works pretty good. Only problem is that you have to press any key + enter. You can't just hit Enter and enter a blank string.

Komarek answered 15/5, 2024 at 18:29 Comment(2)
yes, you can. Set /p is totally happy with an empty input (just ENTER without any key before). The pause command on the other hand does just the opposite: waiting for any key without needing ENTER)Rebellion
Yeah, I actually figured that out and was going to edit this post but forgot. pause is exactly what I needed. Still, the whole "Press any key to continue. " brought me back to my old C++ days. cin<<anykey; // lol amazing how some shit we can't remember and oher stuff we never forget.Komarek

© 2022 - 2025 — McMap. All rights reserved.