Tee

From LQWiki
Jump to: navigation, search

Tee acts as a T-switch, as a duplexer. It takes an input stream and sends it to two output streams. The following example gets a directory listing from stdin and outputs this as well on stdout as into the file terminal.out:

ls -al | tee terminal.out

To verify, do a

cat terminal.out

This is very useful in trainings and debugging.

Using script, you can create a sub-shell and capture all input and output into a logfile.

Using exec within a script, you can redirect output to a logfile: exec 1>logfile 2>&1 But then you cannot see the output on the screen. You can use tee within a script, but it just works within that one line. So, the question is, how do we tell our script to put its output as well on the screen as into a file.

The Answer

How to capture command line screen text output in a logfile and still have it show on the screen

This sample code can be included in an ash/bash shell script:

rm PIPE1
mkfifo PIPE1
#cat >logfile1 <PIPE1 &
cat <PIPE1 &

rm PIPE2
mkfifo PIPE2
cat >logfile2 <PIPE2 &
#cat <PIPE2 &

rm PIPE0
mkfifo PIPE0
tee PIPE1 >PIPE2 <PIPE0 &

exec 1>PIPE0 2>&1

# now all STDOUT and STDERR is copied to logfile2 and is also still sent to the screen

echo starting
lsof -R | grep PI #sample output
echo bye

This is a great way to really get to know mkfifo and tee. After you make a named pipe with mkfifo, you must connect the pipe to an output before you can connect it to an input. The & at the end of the line makes the script keep going while the spawned subtask is running.

Note: This is the hard way to do this. There is a program called script that is supposed to be able to capture all input and output in a spawned sub-shell. And it is also easy to run a script and capture the output:

 sh script.sh 2>&1 | tee logfile

The above example is for situations where you want to be able to do these kinds of dynamic plumping redirections from within a script, operating at the current shell level.

Provided by

Most (all?) Linux distributions incorporate this from the GNU Coreutils and use its man page

Related commands

  • lsof - list open files
  • script - captures all output of an interactive console session.

See also

External links