What is the best way to test ERRORLEVEL in batch?

3

I have already seen several ways to test ERRORLEVEL in batch scripts. Some of them are dangerous and others are wrong, but sometimes they go unnoticed. Here are some examples I know:

  

Dangerous: The test works as "greater than or equal to 1", ignoring negative returns (used in "C" programs). You do not have to worry about limiting block expansion here.

if errorlevel 1 (
   echo Comando executado com problema
)
  

Wrong: test works as "greater than or equal to 0", indicating true for return with or without error

if errorlevel 0 (
   echo Comando executado com sucesso
)
  

Doubtful: tests the result of executing a successful or errored command or batch, respectively. This form is interesting, but it has the issue of limiting expansion in IF / FOR blocks, etc.

if "%ERRORLEVEL%"=="0" (
   echo Comando executado com sucesso
)

if not "%ERRORLEVEL%"=="0" (
   echo Comando executado com problema
)
  • Which of these forms is most appropriate?
  • Is there an even better way not mentioned?
asked by anonymous 10.03.2017 / 18:59

1 answer

3

Probably the last option because of readability and can deal with negative returns.

IF %ERRORLEVEL% EQU 0 ( 
  echo OK
) ELSE ( 
  echo ERRO
)

Another alternative with conditional :

IF %ERRORLEVEL% EQU 0 echo OK || echo ERRO

Bonus : To specify the return of a subroutine, use exit /b [n] , where n is the return code.

    
10.03.2017 / 20:25