Search code examples
batch-filemenuerrorlevel

Batch file %errorlevel% malfunction with `choice` command


I have a menu in a batch file that is powered by the choice command:

choice /C PNQTF /N /M "Choice: "
echo Errorlevel is %errorlevel%
if %errorlevel%==5 goto ViewFTP
if %errorlevel%==4 goto AutoTransferToggle
if %errorlevel%==3 goto TheEnd
if %errorlevel%==2 goto InternalLink
if %errorlevel%==1 goto NewSub
goto begin

19 times out of 20, there are no problems. The menu works fine. But a small percentage of the time, when I push Q to quit, the code seems to randomly skip all the way to :NewSub even though the Errorlevel is %errorlevel% statement echoes to the screen that Errorlevel is 3... and yet it still follows the instructions as if errorlevel were 1!

I thought of maybe using !errorlevel! just to be safe, but it doesn't matter because this set of choices is not in any block of code - it's not enclosed in any if statements or in any functions. I will say this issue never happens if I just run the batch file and immediately quit... there is something in the dark depths of the batch file that is somehow managing to linger and haunt the menu when the execution returns back to the beginning via goto begin.

I am missing half of the hair on my head because this issue has caused me to pull so much of it out. Chest hair might be next. The only thing that would seem more random than this


Solution

  • It turns out the solution is something I had already checked for before, but not careful enough. I traced my code and found a scenario where the user is returned to the main menu (goto begin) while in the middle of a called function - so the function was never concluded with a goto :eof statement.

    Symptoms only occur when the user tries to quit from the main menu. When the user selects Q (which brings them to the very bottom of the file to a label called :TheEnd), it skips right back up to the line after the goto begin statement that interrupted the unconcluded function. The user doesn't see any output other than "after I hit Q, suddenly it's executing this other code."

    So, as it turns out, errorlevel was working just fine; the returning of execution back to that line of code only made it appear that errorlevel was messing up, when in fact the batch file execution was treating the non-completed function like a bucket list item before finally dying.