Overview
`tee` acts as an interceptor in a pipeline, displaying data on the screen while simultaneously saving it to a file. The `-a` option changes this saving behavior to 'append' mode, allowing new data to be added while preserving the existing file content. This is similar to `>>` redirection, unlike `>` which overwrites the file, but `tee` differs in that it continues to pass data to standard output.
Key Features
- Processes standard input and standard output concurrently
- Appends content to files (-a option)
- Controls data flow in the middle of a pipeline
- Can write to multiple files simultaneously
Key Options
The `tee` command offers various options to control how data is written to files. The `-a` option is particularly essential for appending data while preserving existing file content.
Writing Modes
Generated command:
Try combining the commands.
Description:
`tee` Executes the command.
Combine the above options to virtually execute commands with AI.
Usage Examples
Learn how to append data to files in various scenarios using the `tee -a` command.
Appending Content to an Existing File
echo "New log message" | tee -a my_log.txt
Appends the output of the `echo` command to `my_log.txt` while simultaneously displaying it on the screen.
Appending to System Log Files (Using sudo)
echo "[$(date)] System event occurred" | sudo tee -a /var/log/syslog
Use `sudo` with `tee -a` to append content to system log files that require elevated privileges. Direct redirection like `>>` might fail because the shell checks permissions before processing the redirection.
Appending to Multiple Files Simultaneously
ls -l | tee -a file1.txt file2.txt
You can append a single output to multiple files at once.
Logging Script Execution Results
./my_script.sh | tee -a script_output.log
Record all output from a script or command to a file while viewing it on the screen in real-time.
Tips & Precautions
Tips and points to consider for more effective use of the `tee -a` command.
Using with sudo
`tee` is very useful when writing to files that require elevated privileges using `sudo`. Direct redirection like `echo "content" >> /path/to/protected_file` can fail because the shell checks permissions before processing the redirection. `tee` executes with `sudo`'s privileges through the pipe, resolving this issue.
- Correct Usage: echo "content" | sudo tee -a /path/to/protected_file
- Incorrect Usage (Permission Issue): sudo echo "content" >> /path/to/protected_file
Error Handling
`tee` outputs error messages to standard error if a file writing error occurs, but it attempts to continue passing data to the next command in the pipeline. For critical data, consider using shell options like `set -o pipefail` to ensure the entire pipeline fails if any command within it fails.
File Creation
`tee -a` automatically creates the specified file if it does not exist. Therefore, there is no need to create the file beforehand.