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, 2014 at 10:07
  • @Gnouc that will give $?==0 all the time.
    – jimmij
    Sep 30, 2014 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.
    – user14755
    Sep 30, 2014 at 10:41
  • @DarkHeart OP wants grep exit code, not other command.
    – jimmij
    Sep 30, 2014 at 10:46
  • @jimmij - yes sorry, i misread.
    – user14755
    Sep 30, 2014 at 10:52

3 Answers 3


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.

  • As soon as grep matches the whole will stop.
    – Matteo
    Apr 14 at 4:52

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.

  • I had to add a print command 2>&1 | awk '/^Error/{exit_code=1;}/^/{print} END{ exit !exit_code}' to get this to work. Otherwise it gave mea syntax error. Note sure if this is right. Jun 7 at 3:16

You can do it with sed as well!

Here's a function to Print all + Highlight matches + Return exit code (5) if no match found:

  esc=$(printf "\033")
  sed '/'"${pattern}"'/,${s//'$esc'[32m&'$esc'[0m/g;b};$q5' "$@"

$ echo -e "What's up\nMr. Jones?" | search_regex "on\|up"

What's up
Mr. Jones?

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.