4

I'd like to check whether a line printed by a command contains an error message, but I'd like to also print all the output from the command (for make logs). Is there some way to get all the output of a command (unmodified) and an exit code based on the contents of that output? The closest workaround I could think about was my_command | grep -C 99999999 '^Error'.

This is similar but distinct to this question, since I care about the exit code and don't want colouring.

  • How about grep -E '^Error|$'? – cuonglm Sep 30 '14 at 10:07
  • @Gnouc that will give $?==0 all the time. – jimmij Sep 30 '14 at 10:30
  • @jimmij - if you are using bash you can use 'set -o pipefail' and the return code will be not be of grep but the command that failed. – DarkHeart Sep 30 '14 at 10:41
  • @DarkHeart OP wants grep exit code, not other command. – jimmij Sep 30 '14 at 10:46
  • @jimmij - yes sorry, i misread. – DarkHeart Sep 30 '14 at 10:52
6

Use tee and redirect it to stderr

my_command | tee /dev/stderr | grep -q '^Error'

It will save grep exit status and duplicate all the output to stderr which is visible in console. If you need it in stdout you can redirect it there later like this:

( my_command | tee /dev/stderr | grep -q '^Error' ) 2>&1

Note that grep will output nothing, but it will be on tee.

2

You can do this with AWK:

command 2>&1 | awk '/^Error/{exit_code=1;}/^/ END{ exit !exit_code}'

This will print all the output lines and return 0 if it finds Error and return 1 if it doesn't.

  • It should return 0 if it finds a match, and non-zero otherwise. – l0b0 Sep 30 '14 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.