0

If I have a code like this:

@echo off
choice /C BL /M "Clear screen or list actual directory"

if errorlevel 2 goto l
if errorlevel 1 goto b

:l
tree /f
goto final

:b
cls
goto final

:final

I know this actually works, but I'm confused about one thing about the errorlevel parts. I wrote first, the same code, but like this:

if errorlevel 1 goto l
if errorlevel 2 goto b

And that way it won't work properly It will only remember the errorcode 1. If you press the second option is not working.
I'm really wondering why the order of the errors matters, if a batch its supposed to execute line by line, or am i wrong?
In a nutshell, what I want to understand is how the error codes work here

dan1st
  • 12,568
  • 8
  • 34
  • 67
  • 2
    The classic form with `if errorlevel 1` actually is evaluated as ***`if errorlevel is 1 or greater`*** so with the lower number first the 2nd if isn't executed at all. –  Nov 27 '18 at 23:25
  • `If errorlevel 1 If not errorlevel 2` will only fire on 1. – CatCat Nov 27 '18 at 23:39
  • 2
    From the Choice help file: **NOTE:The ERRORLEVEL environment variable is set to the index of the key that was selected from the set of choices. The first choice listed returns a value of 1, the second a value of 2, and so on. If the user presses a key that is not a valid choice, the tool sounds a warning beep. If tool detects an error condition, it returns an ERRORLEVEL value of 255. When you use ERRORLEVEL parameters in a batch program, list them in decreasing order.** – Squashman Nov 27 '18 at 23:41

2 Answers2

2

Just a hint, when using the %errorlevel% variable attached to a goto label, things can be quite easy:

@echo off
choice /C BL /M "Clear screen or list actual directory"
goto :choice%errorlevel%

:choice1 B
tree /f
goto final

:choice2 L
cls
goto final

:final
pause
0
C:\>if /?
...
IF [NOT] ERRORLEVEL number command
...
ERRORLEVEL number   Specifies a true condition if the last program run returned
                    an exit code equal to or greater than the number specified.

In other words, if errorlevel 1 executes for any errorlevel (except 0 = no error) because they're all equal to or greater than 1.

melpomene
  • 84,125
  • 8
  • 85
  • 148