Sam
Sam

Reputation: 389

batch cmd exits as I enter the input with space

I am writing a batch script for an user interface where you can enter the digits 1 - 10. its pretty much like this example:

@echo OFF
:ask
cls
echo press 1 for test1
echo press 2 for test2
set /p input=
if %input% == 1 goto test1
if %input% == 2 goto test2
if %input% GTR 10 goto ask
goto ask
:test1
shutdown
:test2
net view
pause
goto ask

i have if %input% GTR 10 goto ask, and in the end goto ask in global because if someone types something different it will go back to the question. Why does it crash me out of the terminal when I type something different?

Upvotes: 0

Views: 1058

Answers (1)

Stephan
Stephan

Reputation: 56180

if you enter a string with space(s), if syntax will give you a syntax error. Let's look at:

if hello world == string echo xyz

if syntax is: if <value1> <comparator> <value2> command
So hello is value1, world is the comparator - wait - what? world isn't a comparator - Syntax error.

Enclose your values in quoutes to be safe:

if "hello world" == "string" echo xyz

So "hello world" is value1, == is the comparator, "string" is value2 and echo xyz is the command. All goes well.

You may be interested in the choice command, which does it's own error handling and allows only valid keys.

Upvotes: 1

Related Questions