tee - Linux
Overview
The tee
command in Linux reads from the standard input and writes to both standard output and one or more files simultaneously. It is commonly used in shell pipelines to capture the output of a command while still displaying it on the screen. This is particularly useful for logging and debugging.
Syntax
tee [OPTION]... [FILE]...
- [OPTION]: Optional flags that alter the behavior of the command.
- [FILE]: One or more filenames to write to.
The command can take input from a pipeline or can be redirected to read from a file.
Options/Flags
-a
,--append
: Append the output to the given files rather than overwriting them.-i
,--ignore-interrupts
: Ignore interrupt signals (CTRL+C).--help
: Display an informative help message and exit.--version
: Output version information and exit.
Each option modifies the command’s behavior in specific ways, such as appending to files instead of truncating them, which can be crucial for maintaining logs over time.
Examples
-
Write output to a file and display it:
ls -l | tee output.txt
This command lists directory contents in detailed format and writes the output to
output.txt
, as well as displaying it on the terminal. -
Append to an existing file:
date | tee -a output.txt
This example appends the current date and time to
output.txt
without overwriting existing content. -
Using multiple files:
uptime | tee output1.txt output2.txt
This sends the output of the
uptime
command to bothoutput1.txt
andoutput2.txt
. -
Ignoring interrupt signals:
cat | tee -i backup.txt
Here,
tee
will ignore interrupt signals allowing the pipe to handle user interruptions without stopping the logging tobackup.txt
.
Common Issues
- File Overwrites: Without the
-a
flag,tee
will overwrite the file. Always double-check the flags when dealing with important log files. - Permission Errors: If
tee
is unable to write to a file, ensure you have the necessary permissions or usesudo
for elevated permissions.
Integration
tee
is often used in scripting and pipelines:
-
Backup logs while monitoring a command:
some_command | tee log.txt | grep "Error"
This setup allows live monitoring of errors while also logging all command output.
-
Combining with
sudo
for system file editing:echo "127.0.0.1 local.dev" | sudo tee -a /etc/hosts
This example adds a line to
/etc/hosts
with root permissions, useful in scripting environment setups.
Related Commands
cat
: Displays the contents of a file.grep
: Searches for patterns in input.awk
: A powerful text processing tool.
Additional Resources:
- Linux man pages: tee(1)
- GNU coreutils manual: tee invocation
The tee
command provides a simple yet powerful way to handle command outputs in Unix-like systems, enhancing both script functionality and user productivity.