Tee Command
The tee command in Unix-like operating systems is a
powerful utility that reads from standard input and writes to both
standard output and one or more files simultaneously. This allows
you to view the output of a command on your screen while also saving
it to a file for later analysis or logging. It's an essential tool
for shell scripting and command-line operations.
Tee Command Usage Examples
Basic Output Redirection
This is the most common use case: displaying command output to the terminal and saving it to a file.
# Display `ls` output to the user, but also write it to the given file.
ls | tee outfile.txt
Appending Output to a File
Use the -a flag to append the output to the file
instead of overwriting its existing content.
# As above, but append the data; previous file's data remains intact while
# new data is added at the end of the file.
ls | tee -a outfile.txt
Writing to Multiple Files
tee can direct the output to multiple files at once.
# Pipe the standard output of a given command into `tee`, which then displays
# it to the user and sending the data to files `one`, `two`, and `three`.
[COMMAND] | tee one two three
Tee with Root Privileges
Sometimes, writing to system files requires elevated privileges.
tee can be used with sudo to achieve this.
# Workaround to output data to a file, with root privileges.
echo 3 | sudo tee /proc/sys/vm/drop_caches
Tee within Vim
A useful shortcut for piping the current Vim buffer content to a
shell command, like tee.
:w !sudo tee %
This command writes the current buffer (%) to a shell
command, using sudo tee to save it, potentially with
root privileges, to the file currently open in Vim.
Understanding Tee's Functionality
The tee command is named after the T-splitter used in
plumbing, which splits a single pipe into two. In the command line,
it splits the standard output stream. This is incredibly useful for
debugging, logging, and ensuring that you have a record of what was
processed, even if the primary action was elsewhere.