Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...