Choice and error rate?

I am doing 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 will exit. How to prevent this?

+4
source share
2 answers

The expression if errorlevel evaluates to true if the actual error level returned by choice is greater than or equal to the specified value. Therefore, if you press 3, the first if statement will be true and the script will exit. Call help if for more information.

There are two simple workarounds.

First (better) - replace the if errorlevel expression with the actual comparison of the %ERRORLEVEL% system variable with the given value:

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

The second is to change the comparison order:

 if errorlevel 3 goto play if errorlevel 2 goto about if errorlevel 1 goto exit 
+6
source

The easiest way to solve this problem is to use the% errorlevel% value to directly jump 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 
+1
source

All Articles