[grep] grep stream 2, the error message

 

In Unix-like systems, stdout (standard output) is stream 1, and stderr (standard error) is stream 2.
By default, grep reads from stdin, which typically receives stdout — not stderr.

To have grep search the error stream (stderr) instead of stdout, you must redirect stderr (2) into stdin (0), like this:

command 2>&1 >/dev/null | grep "pattern"

Let’s break that down precisely:

  • command — the command whose stderr you want to inspect.

  • 2>&1 — redirects stderr (2) to stdout (1).

  • >/dev/null — discards the original stdout so that only stderr ends up going into the pipe.

  • | grep "pattern" — filters the combined (now pure stderr) stream for the given text pattern.

Example

gcc bad_code.c 2>&1 >/dev/null | grep "error"

This will show only error messages (from stderr) that contain the word “error”.


If you want to only redirect stderr to grep (without destroying stdout), the canonical, cleaner form is:

command 2> >(grep "pattern")

This uses process substitution (a Bash feature) to send just the stderr stream to grep, leaving stdout untouched.

Example

gcc bad_code.c 2> >(grep "warning")

grep filters warnings from stderr, while stdout (if any) still prints normally.


Summary of key variants

PurposeCommand
Search stderr only, discard stdout `command 2>&1 >/dev/null
Search stderr only, keep stdout intact command 2> >(grep "pattern")
Search both stdout and stderr together `command 2>&1

Would you like me to show how to capture the filtered stderr lines in a file as well (for logging or diagnostics)?

 

posted @ 2025-10-23 19:22  profesor  阅读(5)  评论(0)    收藏  举报