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?
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With