CIS120Linux Fundementals
The tee Command
The tee
command in Linux is a versatile tool used for reading from standard input and writing to both standard output and one or more files simultaneously. This command is particularly useful when you need to view the output of a command on the screen while also saving it to a file. The name "tee" is derived from the T-splitter used in plumbing, symbolizing its ability to split the input data stream into two directions. The basic syntax for the tee
command is:
tee [OPTION]... [FILE]...
Common Options for tee
Option | Description |
---|---|
-a |
Append the output to the file instead of overwriting it |
-i |
Ignore interrupt signals |
-p |
Diagnose errors writing to non-pipes |
For example, to write the output of a command to a file and display it on the terminal simultaneously, you can use:
ls -l | tee output.txt
This command lists the directory contents in long format, displays it on the terminal, and writes it to output.txt
. If you want to append the output to an existing file instead of overwriting it, use the -a
option:
ls -l | tee -a output.txt
This command appends the directory listing to output.txt
without overwriting the existing content. The -i
option is used to ignore interrupt signals, ensuring that the tee
command continues to run even if you accidentally press Ctrl+C
:
ls -l | tee -i output.txt
The tee
command can also be used to write output to multiple files. For instance:
ls -l | tee output1.txt output2.txt
This command writes the output of ls -l
to both output1.txt
and output2.txt
, while still displaying it on the terminal.
Examples
Writing output to a file and terminal:
echo "Hello, World!" | tee hello.txt
Appending output to an existing file:
echo "Additional line" | tee -a hello.txt
Ignoring interrupt signals:
ls -l | tee -i filelist.txt
Writing output to multiple files:
echo "Multi-file output" | tee file1.txt file2.txt
Listing all files in a directory, saving to getall.txt
, and filtering lines containing "hello" to hello.txt
:
ls -l | tee getall.txt | grep "hello" > hello.txt
Summary
The tee
command is a powerful and flexible utility for duplicating the output of a command, allowing it to be both displayed on the terminal and saved to one or more files. This dual functionality makes it an invaluable tool for tasks such as logging command output or capturing real-time data for later analysis. Understanding and utilizing the tee
command's options can greatly enhance your ability to manage and redirect command output effectively in a Linux environment.