Send output of a bash script to the console and to a file

Sometimes it is necessary to send the output of a script to different targets. If you want to send the output to a text but want to be able to see it on the console as well you can use the tee command.
Here is an example on how to use it in a bash script:

exec > >(tee $OUTPUTFILE)
 exec 2>&1

The first line uses process substitution to create a pipe which will then be connected to a tee process. The first > is the redirection of the file descriptor(1 stands for stdout) and the second > in combination with the () does the process substitution.
The second line redirects the stderr(2) file descriptor to whatever number 1 is already redirected to.

About Juergen Caris

I am 54yo, MSc(Dist) and BSc in Computer Science, German and working as a Senior Server Engineer for the NHS Lothian. I am responsible for the patient management system, called TrakCare. I am a UNIX/Linux guy, working in this sector for more than 20 years now. I am also interested in robotics, microprocessors, system monitoring, Home automation and programming.
This entry was posted in Bash, Beginner. Bookmark the permalink.

Leave a Reply

Your email address will not be published.