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