Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a script that outputs text to stdout. I want to see all this output in my terminal, and at the same time I want to filter some lines and save them in a file. Example:

$ myscript
Line A
Line B
Line C

$ myscript | grep -P 'A|C' > out.file

$ cat out.file
Line A
Line C

I want to see output of first command in terminal, and save the output of the second command in a file. At the same time. I tried using tee, but with no result, or better, with reversed result.

share|improve this question
up vote 11 down vote accepted

I want to see output of first command in terminal, and save the output of the second command in a file.

As long as you don't care whether what you are looking at is from stdout or stderr, you can still use tee:

myscript | tee /dev/stderr | grep -P 'A|C' > out.file

Will work on linux; I don't know if "/dev/stderr" is equally applicable on other *nixes.

share|improve this answer
Nice trick! It works, thanks! – lorenzo-s Apr 6 '13 at 19:06
/dev/stderr is common. /dev/tty (meaning the current terminal) would also work here, and it's standard. – Gilles Apr 6 '13 at 23:42
@Gilles: Wonderful. tee /dev/tty served wonderfully for my requirement of having to print the stdout of a script to terminal and to pipe it to the stdin of another command as well! Thankees! :-) – jamadagni Jun 7 '14 at 1:09
{ ... | tee /dev/fd/3 | grep -e A -e C > out.file; } 3>&1

Or with process substitution (ksh93, zsh or bash):

... | tee >(grep -e A -e C > out.file)

With zsh:

... >&1 > >(grep -e A -e C > out.file)
share|improve this answer

Here's another way with sed:

myscript | sed '/PATTERN/w out.file'

By default, sed prints every line so in this case stdout will be the same as stdin (i.e. you'll see the entire output of myscript on screen).
In addition, all lines matching PATTERN will be written to out.file

share|improve this answer

you didn't specify how you used the tee command but this should work:

myscript | grep -P 'A|C' | tee out.file

at least it worked on my server few minutes ago...

share|improve this answer
But, if I'm not wrong, this way you grep also what's on screen. I want to see all output on screen, and filter only what's going into the file. – lorenzo-s Apr 6 '13 at 19:03

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.