26

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?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • 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 09 '17 at 07:37

1 Answers1

42

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
Michael Mrozek
  • 93,103
  • 40
  • 240
  • 233
  • 10
    And for extra bash 4 cuteness: prog |& tee file. – Tobu Nov 19 '10 at 01:49
  • 1
    You can also replace 'file' with a named pipe... – Kevin Cantu Nov 30 '10 at 02:09
  • 1
    @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 09 '17 at 07:44