Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choice and Errorlevel?

Tags:

batch-file

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?

like image 607
user1464566 Avatar asked Jun 18 '12 18:06

user1464566


People also ask

What does Errorlevel mean?

In Microsoft Windows and MS-DOS, an errorlevel is the integer number returned by a child process when it terminates. Errorlevel is 0 if the process was successful. Errorlevel is 1 or greater if the process encountered an error.

What is %% A in batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

What is P in batch file?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.


2 Answers

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
like image 76
Helbreder Avatar answered Oct 12 '22 22:10

Helbreder


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
like image 29
Aacini Avatar answered Oct 12 '22 22:10

Aacini