Search code examples
bashgrepexit-code

compute exit code based on text output


I have a program which returns always zero exit code, even in case of an internal error. In case of an error there is additional output to standard output like:

# always-zero-exit
Error: Line: 1, Column: 1
some further scary error description....

Can someone please advice how to make a short bash workaround like the one below:

# always-zero-exit > search-for-string-'Error'-and-returns-non-zero-if-found

Solution

  • As Biffen suggested in the comment, use ! grep ERROR_PATTERN.

    Example:

    # Tiny test command that exit with status 0 and 
    # prints errors into STDOUT:
    
    echo 'Error: Line: 1, Column: 1' > out.log
    ! grep -q 'Error' out.log
    echo $?
    # Prints: 1
    
    # Same, no errors:
    
    echo 'Line: 1, Column: 1' > out.log
    ! grep -q 'Error' out.log
    echo $?
    # Prints: 0
    

    You may want to use more complex error message processing, for example:

    ! grep -Pqi '(error|fail|exception)' out.log
    

    Here, grep uses the following options:
    -P : Use Perl regexes.
    -i : Use case-insensitive matching.
    -q : Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found.

    SEE ALSO:
    grep manual