Redirect to File and Print Output to CLI Using Tree

Using tee command to redirect to file while printing output to screen simultanously.

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 command
  • tee - redirects to file (overwrite); use -a flag to append instead
About the author

Arapi Tech

Networking + DevOps + Programming

Arapi Tech Blog

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Arapi Tech Blog.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.