23

Okay. If I wanted to redirect the output of a program to a file, I'd do something like this

prog > file

If I wanted to redirect both stdout and stderr to that file, then I'd do

prog > file 2>&1

This is all well and good if you want the output to go to the file. But what if you want the output to go to the file and yet still go to stdout/stderr? So, the output is saved in the file, but you can still see it on the console as the program is running. Is there a way to do that? And if so, how?

  • Terminology: You mean and still go to the terminal. stdout is file-descriptor 1, and foo > some_file means that a write-only file descriptor opened on some_file is foo's stdout. stdout always goes to stdout. – Peter Cordes Jun 9 '17 at 7:37
38

tee exists for this purpose; it takes a filename argument and writes the data it reads from stdin to both stdout and the file:

$ prog 2>&1 | tee file
  • 9
    And for extra bash 4 cuteness: prog |& tee file. – Tobu Nov 19 '10 at 1:49
  • 1
    You can also replace 'file' with a named pipe... – Kevin Cantu Nov 30 '10 at 2:09
  • @KevinCantu: A named pipe is just one type of file; this is Unix where everything is a file. You can also prog |& tee /dev/tty > file, which can be useful in the middle of a pipeline, e.g. foo |& tee /dev/tty | sed 's/.*\r//' > foo.log to see status-line progress updates on your terminal, but filter them out of a log file. Or use it to debug a pipeline you're hacking together by letting you see the data at that point. – Peter Cordes Jun 9 '17 at 7:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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