Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Batch Files - User Input
- The "set" command is also able to pass user input.
- This is done by set /p.
- For example:
- @echo off
- echo Type something!
- set /p test="Input :"
- exit
- test is the variable. "Input :" is printed on the screen and prompts the user for input.
- If you just type this in a batch. The user can type anything he wants.
- To narrow this down, you can use the "IF" statement and check if the user typed what he was supposed
- to.
- The following code does this:
- @echo off
- echo Type s to exit this batch!
- set /p test="Input :"
- if %test%==s ( echo Good job
- ) else ( echo You did not type the correct letter! )
- pause > nul
- exit
- What this does is it prompts the user to write something, if this is not the letter s, the if statement check fails and prints
- "You did not type the correct letter!".
- > nul quashes the output of any text by not sending it to the CLI.
- One way to extent this code is to add an option to it that gives the user three tries to type the wanted letter. This can be achieved by working with
- jumpmarks and if statements.
- @echo off
- echo Type q. You have three tries!
- set /p input="Type: "
- if %input%==q ( goto JUMP ) else ( goto IF1 )
- :IF1
- echo You have two more tries!
- set /p input="Type: "
- if %input%==q ( goto JUMP ) else ( goto IF2 )
- :IF2
- echo You have one more try!
- set /P input="Type: "
- if %input%==q ( goto JUMP ) else ( goto FAIL )
- :FAIL
- echo You failed!
- pause>nul
- exit
- :JUMP
- echo Well done!
- pause>nul
- exit
- The following batch asks the user over and over again to type the right letter, by just setting a jumpmark at the very beginning of the code.
- @echo off
- :J1
- echo Type s to start a program!
- set /p var1="Input:"
- if %var1%==s ( goto J2 ) else ( goto J1 )
- :J2
- echo Well done! That was just a test!
- pause
- exit
- Note: The input-variable can be empty, you don´t need to specify a string.
- set /p input=
- Which displays nothing.
Advertisement
Add Comment
Please, Sign In to add comment