Search code examples
windowsbatch-filefindstrerrorlevel

Best way to check errorlevel


I am writing a batch script to be run in Win 10 OS. However I am facing issues with checking errorlevel of exist status of a Windows command. Faintly I decided to use below way:

findstr /I /C:"EXIT_FAILURE" /I /C:"UNKNOWN" file 
if '%ERRORLEVEL%'=='0' goto CHECKFAILED

findstr /I /C:"EXIT_SUCCESS" file 
if '%ERRORLEVEL%'!='0' goto CHECKFAILED

exit /B 0

:CHECKFAILED
exit /B 2

Is it the right way to check - I mean compare errorlevel as string or using within single quotes?

The errorlevel when validated for its numeric values leads to understanding considerations that command provides like:

if ERRORLEVEL 0

would mean TRUE for ERRORLEVEL >=0. Similarly there are other considerations.

Hence is it right to use ?& compare ERRORLEVEL as string as mentioned above?


Solution

  • Here's an alternative approach using conditional operators, && and ||. It is based upon your previous post, which appears to be related to the same question, 'the use of errorlevels'.

    The conditional operators work a little like:

    • && 'if the previous command succeeded'
    • || 'if the previous command failed'.
    @Echo Off
    If "%~4"=="" Exit /B 1
    If Not Exist "%~3" Exit /B 1
    If Not Exist "%~2\%~1" Exit /B 1
    If Not Exist "%__APPDIR__%findstr.exe" Exit /B 1
    
    Set "arg1=%~1"
    Set "logfile=%~3\%~4.%arg1:.=_%.res"
    
    Copy /V /Y "%~2\%~1" "%logfile%" 1>NUL 2>&1 || Exit /B 1
    
    Set "findstr=%__APPDIR__%findstr.exe"
    Set "errno=0"
    
    "%findstr%" /I "EXIT_FAILURE UNKNOWN" "%logfile%" 1>NUL 2>&1 && (Set "errno=2"
    ) || "%findstr%" /I "PASS" "%logfile%" 1>NUL 2>&1 || Set "errno=2"
    
    Exit /B %errno%
    

    So if the command is successful, i.e. at least one of the strings was matched, it will perform the set command, i.e. define an error number value. If the findstr command failed, i.e. neither string was matched, the set command would also have failed to define an error number value, meaning that the second findstr command would be ran. If the second findstr command doesn't match the string, the error number value will be set, otherwise the default value of 0 would remain in place.