1

We have some error handling setup in our scripts as shown:

set ret = %ERRORLEVEL%
if %ERRORLEVEL% == 0 GOTO PPCOK
if not %ret% == 0 GOTO ERROR1

Someone else wrote the above, I however have a few concerns about it actually working properly.

  1. I have read that if you do a check for ERRORLEVEL = 0 it actually is checking if the errorlevel is 0 or higher. My assumption is that it would always go to the PPCOK label?

  2. Also, most examples on the web use "IF ERRORLEVEL 1" or some show "IF %ERRORLEVEL% EQU 1" and above uses "IF %ERRORLEVEL% == 0" I am wondering if there is a valid case for choosing which of these three methods should be used?

On a side note I am not sure why they stored the errorlevel in another variable and used it on the second if statement rather than just doing another IF NOT %ERRORLEVEL% ...

1
  • No, if %ERRORLEVEL% == 0 will only be true if the error level is actually zero. This method is usually preferable in my opinion, although it will fail in the pathological case where someone has created an environment variable named ERRORLEVEL. You are right in thinking that there is no need for the ret variable, in fact the second if statement is entirely redundant, you could just say GOTO ERROR1. Commented Feb 4, 2014 at 2:56

1 Answer 1

1

Batch is sensitive to spaces in a SET statement. SET FLAG = N sets a variable named "FLAGSpace" to a value of "SpaceN"

IF ERRORLEVEL n is TRUE if errorlevel is n or greater than n. IF ERRORLEVEL 0 is therefore always true. IF NOT ERRORLEVEL 1 is a test for errorlevel=0. So is IF %ERRORLEVEL%==0, exept that the former can be used within a block but the latter cannot.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, the error level is treated as a signed quantity. So if errorlevel 0 is not always true, and if not errorlevel 1 will be true if the error level is negative as well as if it is zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.