Saving and forwarding output with tee
- Version
- unversioned
- Review
- Draft
Summary#
tee copies standard input to standard output and to each file you name. Put it in a pipeline to save a copy while downstream commands still receive the data.
Syntax#
command | tee output.log
command | tee -a output.log
command 2>&1 | tee output.log
-a appends to an existing log. Use 2>&1 on the producing command to include its standard error in the pipe.
Example#
(
set -eu
dir=$(mktemp -d)
trap 'rm -rf -- "$dir"' EXIT
cd "$dir"
printf 'queue ready\n' | tee run.log | tr '[:lower:]' '[:upper:]'
printf 'worker started\n' | tee -a run.log >/dev/null
echo '-- saved log'
cat run.log
)
Expected output#
QUEUE READY
-- saved log
queue ready
worker started
Common mistakes#
tee truncates existing destinations unless you use -a. Keep the input and output files separate. A pipeline such as sort data | tee data can erase the input before sort reads it.
Version applicability#
The forms shown use POSIX tee options and work with GNU coreutils and macOS tee.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0