Michael Harvey
Michael Harvey

Reputation: 148

Detect [Enter] key in bat file

I give my users a couple of options, then wait for their input. In my testing when I hit the [Enter] key with putting in any selection the program will crash and burn. It gives me the error "( was unexpected at this time." How can I detect if user solely presses the [Enter] key?

Here's what I have.

:pickClient
set clientNum=
cls
echo.
echo  Pick a Client
echo.
echo.
echo    1. Client 1
echo.
echo    2. Client 2
echo.
echo.
echo   [E] - EXIT
echo.
set /p clientNum=Input selection.  

if %clientNum%==1 (

     set client=client1Name

) else if %clientNum%==2 (

     set client=client2Name

) else if /i %clientNum%==E (

     GOTO goAway

) else if %clientNum%==" " (

     GOTO pickClient

) else (

     GOTO pickClient

)

Upvotes: 1

Views: 5865

Answers (2)

Michael Harvey
Michael Harvey

Reputation: 148

I figured it out! Here's what I did.

set clientNum=
cls
echo.
echo  Pick a Client
echo.
echo.
echo    1. Client 1
echo.
echo    2. Client 2
echo.
echo.
echo   [E] - EXIT
echo.
set /p clientNum=Input selection.  

IF NOT DEFINED clientNum GOTO pickClient  <---I added this line of code. *****

if %clientNum%==1 (

     set client=client1Name

) else if %clientNum%==2 (

     set client=client2Name

) else if /i %clientNum%==E (

     GOTO goAway

) else if %clientNum%==" " (

     GOTO pickClient

) else (

     GOTO pickClient

)

UPDATE:

Thanks to @ths's helpful input, I've found that I should start using quotes when testing variables. Through my own testing I found that the following works just as well as testing for DEFINED.

set clientNum=
cls
echo.
echo  Pick a Client
echo.
echo.
echo    1. Client 1
echo.
echo    2. Client 2
echo.
echo.
echo    [E] - EXIT
echo.
set /p clientNum=Input selection.  

if "%clientNum%"=="1" (

     set client=client1Name

) else if "%clientNum%"=="2" (

     set client=client2Name

) else if /i "%clientNum%"=="E" (

     GOTO goAway

) else if "%clientNum%"==" " (

     GOTO pickClient

) else if "%clientNum%"=="" (

     GOTO pickClient

) else (

     GOTO pickClient

)

NOTE the quotes. Give some love to ths by up-voting his input. I'm greatly appreciative of it.

Upvotes: 1

ths
ths

Reputation: 2942

if you just press enter, the variable is empty and your comparisons

if %clientNum%==1 (

become

if ==1 (

which is illegal. to prevent problems like this, or spaces in variable values, it is prudent to always surround the variables and values in the if with quotes:

if "%clientNum%"=="1" (

then becomes

if ""=="1" (

which is a valid statement.

Upvotes: 4

Related Questions