user1464566
user1464566

Reputation: 81

Choice and Errorlevel?

I do something like this:

echo 1-exit
echo 2-about
echo 3-play
choice /c 123 >nul
if errorlevel 1 goto exit
if errorlevel 2 goto about
if errorlevel 3 goto play
:play
blah
:about
blah
:exit
cls

If I select the "play" option, it exits. How do I prevent this from happening?

Upvotes: 8

Views: 15122

Answers (2)

Aacini
Aacini

Reputation: 67196

The easiest way to solve this problem is to use the %errorlevel% value to directly go to the desired label:

echo 1-exit
echo 2-about
echo 3-play
choice /c 123 >nul
goto option-%errorlevel%
:option-1
rem play
blah
:option-2
rem about
blah
:option-3
exit
cls

Upvotes: 4

Helbreder
Helbreder

Reputation: 922

The if errorlevel expression evaluates to true if actual error level returned by choice is greater or equal to given value. So if you hit 3, the first if expression is true and script terminates. Call help if for more information.

There are two simple workarounds.

First one (better) - replace if errorlevel expression with actual comparision of %ERRORLEVEL% system variable with a given value:

if "%ERRORLEVEL%" == "1" goto exit
if "%ERRORLEVEL%" == "2" goto about
if "%ERRORLEVEL%" == "3" goto play

Second one - change order of comparisions:

if errorlevel 3 goto play
if errorlevel 2 goto about
if errorlevel 1 goto exit

Upvotes: 13

Related Questions