Shell Script – How to Capture Stdout/Stderr in File and Console

shellshell-scriptstderrstdout

I'm using bash script on AMazon Linux. When I want to redirect stderr and stdout to a file, I can run

./my_process.pl &>/tmp/out.txt

Is there a way I can redirect this output to a file and continue to see it on the console (in my shell)? How is this done?

Best Answer

Yes, by using tee:

/my_process.pl 2>&1 | tee /tmp/out.txt

Note that using &>file for redirecting both standard output and standard error to a file is an extension to the POSIX standard that is accepted by some shells. It is safer to use >file 2>&1. In this case, &> can not be used at all since we're not redirecting to a file.

In bash, one may also do

/my_process.pl |& tee /tmp/out.txt

which is equivalent of the above. In ksh93, |& means something completely different though.