What is the most appropriate way to batch test ERRORLEVEL?

Asked

Viewed 6,483 times

4

I’ve seen several forms of testing ERRORLEVEL in batch scripts. Some of them are dangerous and others are wrong, but sometimes go unnoticed. Below are some examples I know:

Dangerous: the test works as "greater than or equal to 1", ignoring negative returns (used in programs in "C"). Here you don’t have to worry about limiting block expansion.

if errorlevel 1 (
   echo Comando executado com problema
)

Wrong: the 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 command or batch successfully and error, respectively. This form is interesting, but there is the question 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 more suitable?
  • There is an even better unquoted form?

1 answer

4


Probably the last option because of the readability and enable dealing 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.