Error - "goto was unexpected at this time" When leaving a blank field and just hitting enter - Batch

StackOverflow https://stackoverflow.com/questions/20638405

  •  18-09-2022
  •  | 
  •  

Question

The problem is when running the game, if I leave the field blank and just hit enter, the window closes.
When running the game in Command Prompt window from directory (to stop it closing), I see the above error message.
The "invalid selection" 'goto start' works fine if a character is entered, it all has to do with there being a blank field.

I have:

  1. tried if not defined goto
  2. tried encasing variables in ""

But nothing seems to work!

:start
cls
echo You need to decide NOW, are you going to barricade yourself in (Bug in),
echo or go to somewhere out of town (Bug out)?
echo.
set /p bug=I want to bug 
if %bug%==In goto bugin
if %bug%==Out goto bugout
if %bug%==in goto bugin
if %bug%==out goto bugout
echo.
echo Invalid selection
pause
cls
goto start
Was it helpful?

Solution

If the user inputs something blank the if statement fails:

set var=
if %var%==blah Echo BLAH
Rem The above results in :: if ==blah Echo BLAH :: Which will crash CMD

set var=
if "%var%"=="blah" Echo BLAH
Rem The above results in :: if ""=="blah" Echo BLAH :: Which will result in false

So surrounding the statement in quotes will result in:

:start
cls
echo You need to decide NOW, are you going to barricade yourself in (Bug in),
echo or go to somewhere out of town (Bug out)?
echo.
set /p bug=I want to bug 
if "%bug%"=="In" goto bugin
if "%bug%"=="Out" goto bugout
if "%bug%"=="in" goto bugin
if "%bug%"=="out" goto bugout
echo.
echo Invalid selection
pause
cls
goto start

Which should work.

Mona

OTHER TIPS

As an extra suggestion, with the /i case insensitive switch then these lines can be replaced with the two lines following them and case will not matter.

if "%bug%"=="In" goto bugin
if "%bug%"=="Out" goto bugout
if "%bug%"=="in" goto bugin
if "%bug%"=="out" goto bugout

if /i "%bug%"=="In" goto bugin
if /i "%bug%"=="Out" goto bugout
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top