I've seen several ways of testing the
ERRORLEVEL in batch scripts. Some of them are dangerous and some are wrong, but sometimes they go unnoticed. Here are some examples I know of:
Dangerous: the test works as "greater than or equal to 1", ignoring negative returns (used in "C" programs). Here you don't have to worry about the block expansion limitation.
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 with success and error, 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 ways is more suitable?
- Is there an even better way not mentioned?
Probably the last option because of readability and being able to 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.