1

When I run an arbitrary command in the terminal in linux, is there a way to suppress output messages that contain a certain sentence?

I tried

./mycommand | grep -v "I dont want to see this"

but the messages were still there.

1
  • I guess you want ./mycommand |& grep -v "I dont want to see this"?
    – kos
    Mar 15, 2016 at 22:47

2 Answers 2

6

Maybe the unwanted part is part of the output to stderr but to stdout.

Try:

./mycommand 2>&1 | grep -v "I dont want to see this"

You can pipe stderr and stdout to different targets. So you may see where the output comes from:

./mycommand > >(grep -v "I dont want to see this" > stdout.log) 2> >(grep -v "I dont want to see this" > stderr.log)

6
  • 2
    Also note that Bash has |&, which is a shorthand for 2>&1 |.
    – kos
    Mar 15, 2016 at 22:49
  • Thanks, that did it, but now it appears to print blank lines instead of those messages.
    – spiderface
    Mar 15, 2016 at 22:53
  • It appears to be a command-specific problem. It outputs an error message and a blank line right after it. Now that I filter out the messages, it only outputs the blank lines. Is there a way to get rid of those lines too?
    – spiderface
    Mar 15, 2016 at 23:00
  • pipe the stderr and stdout to different files to see where the empty lines come from - I did an edit to explain how
    – cmks
    Mar 15, 2016 at 23:09
  • I was able to filter out blank lines and unwanted messages using ./mycommand 2>&1 | grep -v -e '^$' -e 'unwanted message' where -e '^$' checks for empty lines and -e 'unwanted message' checks for the messages that I want to suppress.
    – spiderface
    Mar 16, 2016 at 2:10
1

To add to cmks' answer, if you also want the return code to be the one from mycommand and not from grep, you can use pipefail and ignore the return status from grep (for when the string to suppress isn't found)

(set -o pipefail; (./mycommand  2>&1) | { grep -v "I dont want to see this" || true; })

Examples:

  • (set -o pipefail; (echo "REMOVE" && false 2>&1) | { grep -v "REMOVE" || true; })

    • stdout: nada
    • return: 1
  • (set -o pipefail; (echo "REMOVE" && true 2>&1) | { grep -v "REMOVE" || true; })

    • stdout: nada
    • return: 0
  • (set -o pipefail; (echo "KEEP" && false 2>&1) | { grep -v "REMOVE" || true; })

    • stdout: KEEP
    • return: 1
  • (set -o pipefail; (echo "KEEP" && true 2>&1) | { grep -v "REMOVE" || true; })

    • stdout: KEEP
    • return: 0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .