Reputation: 11
New to the site and to scripting in general. I am aware that you can create user inputs like this:
set input=
set /p input=[y/n]: %=%
then you can ask using "if" to see if they are certain responses. Example:
if "%input%"=="y" goto a:
and check if it isn't said input by saying
if "%input%" NEQ "y" goto b:
Because I'm uneducated, I don't know how to accomplish this, but I want to be able to determine if the input was an enter keystroke. I have tried to accomplish this by using
if "%input%"==[ENTER] goto a:
and
if "%input%"==enter
and every method I could think of to determine if the keystroke was an [ENTER]. I am probably just stupid, but is there a way to do this? Thanks.
Upvotes: 1
Views: 1985
Reputation: 70923
There are at least two ways to do that: check the value or check the operation
set /p
retrieves the typed input storing it inside a variable, but when there is no input, just an Enter press, there is no storage operation on the variable so it keeps its previous value.
The usual way to test the value is to clear the variable contents, use the set /p
and test if the variable is defined, that is, it has content
set "var="
set /p "var=[y/n]?"
if not defined var goto :noUserInput
We can also test the operation itself. In batch files most of the commands set to some value the internal errorlevel
variable indicating the sucess or failure of the execution of the command.
In the case of the set /p
it will set errorlevel
to 0 if data has been retrieved and will set it to 1 if there is no input. Then the if errorlevel
construct can be used to determine if there was input
set /p "var=[y/n]?"
if errorlevel 1 goto :noUserInput
As Aacini points, this can fail. If the batch file has .bat
extension a set /p
that reads data will not reset (set to 0) a previous errorlevel
value, so it is necessary to first execute some command to set the errorlevel
to 0.
ver > nul
set /p "var=[y/n]?"
if errorlevel 1 goto :noUserInput
If the batch file is saved with .cmd
extension this is not needed. In this case the set /p
will set the errorlevel
to 0 when it reads data.
Also conditional execution operators (&&
and ||
) can be used. &&
executes the next command if the previous one was sucessful. ||
will execute the next command if the previous one failed.
set /p "var=[y/n]?" || goto :noUserInput
Upvotes: 5
Reputation: 79983
If not defined input ...
detects whether input
has an assigned value.
Coding
set "input="
set /p "input=[y/n]: "
if not defined input echo Enter alone detected
should detect the enter key alone being operated.
The syntax set "var=string"
ensures that trailing spaces on the line are not included in the value assigned (they're hard to see).
Note that a response of simply Enter will leave the target variable unchanged; it will not assign nothing to the variable. For this reason, it is wise to ensure that the variable is cleared before a manual entry.
Upvotes: 1