Main index

Introducing UNIX and Linux


Getting started

Overview
Using UNIX
      Usernames
      Logging in
Logging out
Commands
      Typing in commands
      Commands and options
Communication with other users
      Email
      Other communication facilities
Files
      The editor Vi
            Vi commands (command mode)
            Vi commands (colon mode)
      Other editors
Input and output
      Scripts
      Here-documents
      Pipes
      Making copies of input and output
      Pagers
Emergencies
Getting help
Summary
Exercises

Making copies of input and output

Suppose you have a command that displays something on your screen, and you wish to save it in a file. So far, we have discussed only how that output can be redirected to a file, so that in order to see it on the screen and save it in a file there are two possibilities. Firstly, you could run the command twice (the first time with no redirection, and then directed to a file). Secondly you initially run the command with output sent to a file and then view the file using a pager. Both methods involve duplicating the output to the command, firstly by producing it twice, and secondly by storing it and then viewing the stored output.

The first method is no use if the command you run is interactive, conducting a dialogue with you while it is running. If you ran the command twice you might give it different input each time, so the two outputs would probably differ. If your command was time-sensitive, such as date, the second method would simply give you the wrong answer when you tried to view the output.

If you wish to make a copy in a file of the input to a command, there would also be a problem. If the command is interactive, so that we cannot store the input in an intermediate file, we have not yet met any mechanism at all which will perform this task.

The solution is to use the command tee. which duplicates the standard input so:

tee copy_of_input | command_name

This has the same effect as the command command_name on its own, except that a copy of all the standard input to the command is sent to copy_of_input (which will be overwritten if it already exists).

Worked example

Send user jo a message and keep a copy of the message in file jo_message.
Solution: mailx will read standard input as the message; use tee to copy it:

tee jo_message | mailx jo

To use tee to copy standard output, pipe the output of a command through tee.

Worked example

Run the command who, but store a copy of the output in file who_out.
Solution:

who | tee who_out


Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck