Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash command to grep something on stderr and save the result in a file

Tags:

bash

shell

I am running a program called stm. I want to save only those stderr messages that contain the text "ERROR" in a text file. I also want the messages on the console.

How do I do that in bash?

like image 375
user2339933 Avatar asked May 01 '13 15:05

user2339933


People also ask

How do I redirect stderr to a file in Linux?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.

Can you read from stderr?

STDERR_FILENO is an output file descriptor. You can't read from it.


2 Answers

Use the following pipeline if only messages containing ERROR should be displayed on the console (stderr):

stm |& grep ERROR | tee -a /path/to/logfile

Use the following command if all messages should be displayed on the console (stderr):

stm |& tee /dev/stderr | grep ERROR >> /path/to/logfile

Edit: Versions without connecting standard output and standard error:

stm 2> >( grep --line-buffered ERROR | tee -a /path/to/logfile >&2 )
stm 2> >( tee /dev/stderr | grep --line-buffered ERROR >> /path/to/logfile )
like image 193
nosid Avatar answered Oct 18 '22 20:10

nosid


This looks like a duplicate of How to pipe stderr, and not stdout?

Redirect stderr to "&1", which means "the same place where stdout is going". Then redirect stdout to /dev/null. Then use a normal pipe.

$ date -g
date: invalid option -- 'g'
Try `date --help' for more information.
$
$ (echo invent ; date -g)
invent                                    (stdout)
date: invalid option -- 'g'               (stderr)
Try `date --help' for more information.   (stderr)
$
$ (echo invent ; date -g) 2>&1 >/dev/null | grep inv
date: invalid option -- 'g'
$ 

To copy the output from the above command to a file, you can use a > redirection or "tee". The tee command will print one copy of the output to the console and second copy to the file.

$ stm 2>&1 >/dev/null | grep ERROR > errors.txt

or

$ stm 2>&1 >/dev/null | grep ERROR | tee errors.txt
like image 3
Alan Porter Avatar answered Oct 18 '22 20:10

Alan Porter