Shell IO Redirection – Redirect Program Output While Keeping It in Stdout

io-redirectionshell

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?

Best Answer

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