The tee
command in Linux is used to read from standard input and write to standard output and files simultaneously. It effectively duplicates the output, allowing it to be seen on the terminal while also saving it to a file. This can be particularly useful for logging output while still viewing it in real-time.
Redirect output to file + print on screen
Output is most commonly redirected using the >
(overwrite) or >>
(append) commands. What if you want to print out this output simultaneously?
- Use the
tee
without any flags to overwrite the output. - Use the
tee
command with the-a
flag to append the output.
Simple redirect example using tee
:
echo "sample output" | tee myFile.txt # Overwrite
echo "sample output" | tee -a myFile.txt # Append
Redirecting stdout + stderr using tee
:
./myScript.py 2>&1 | tee myFile.txt # Overwrite
./myScript.py 2>&1 | tee -a myFile.txt # Append
2
- captures stderr>
- redirects the captured stderr&1
- redirects the captured stderr into stdout, combining both|
- pipes the output of previous command into the next commandtee
- redirects to file (overwrite); use-a
flag to append instead