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

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 need messages on the console.

How to do this in bash?

+7
source share
3 answers

Use the following pipeline if 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 ) 
+13
source

It looks like a duplicate. How do I pass stderr, not stdout?

Redirect stderr to "& 1", which means "the same place where stdout goes." Then redirect stdout to / dev / null. Then use a regular handset.

 $ 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> redirection or "tee". The tee command prints one copy of the output to the console and a second copy of the file.

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

or

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

You say you want stderr and stdout to appear in the console, but only stderr (not stdout), which contains "ERROR" to enter the file? This is the last condition that makes it difficult to find an elegant solution. If this is what you are looking for, here is my very ugly solution:

 touch stm.out stm.err stm 1>stm.out 2>stm.err & tail -f stm.out & tail -f stm.err & \ wait `pgrep stm`; pkill tail; grep ERROR stm.err > error.log; rm stm.err stm.out 

I warned you that this is ugly. You can hide it in a function, use mktemp to create temporary file names, etc. If you do not want to wait for stm to exit before writing ERROR text to a file, you can add tail -f stm.err | grep ERROR > error.log & tail -f stm.err | grep ERROR > error.log & after the other tail commands, and remove the grep command from the last line.

0
source

All Articles