Live Chat!

How to redirect output to a file as well as display it out

* * * * ½ 3 votos

December 6th, 2007 mysurface Posted in Text Manipulation, pipeline, python, tee | Hits: 45942 |

To redirect standard output to a file is easy, you just need to use the redirection symbol, for example:

echo "hello world" > test.txt

But what if I want to display it out as well as store into a file?
Answer: tee

echo "hello world" | tee test.txt

Okay it seems very easy, how about append?

To append the standard output to a file, you do this:

echo"hello world" >> test.txt

Append to file and display it out as well?

echo"hello world" | tee -a test.txt

Okay, how about dealing with standard output(stdout) and standard error(stderr)?
There are two different output stream, one is stdout and another one is stderr. Normal print usually goes to stdout and error related message will goes to stderr. Lets make a simple python script to print 1 line to stdout and 1 line to stderr.

#!/usr/bin/env python

import sys

sys.stdout.write("I am stdout\n")
sys.stderr.write("I am stderr\n")

Ok, lets save the python script as sout.py and try to redirect the output to a file.

$ ./sout.py > test.txt
I am stderr

Standard output is redirect to test.txt but stderr is print out.

What if I want stderr to be redirect and display the stdout?

 ./sout.py 2> test.txt

I want both stored into the file.

 ./sout.py 2&> test.txt

At last, I want both display and redirect to a file:

 ./sout.py 2>&1 | tee test.txt

Interesting isn’t it?

6 Responses to “How to redirect output to a file as well as display it out”

  1. Wot if I want to redirect same output to two files without displaying it and without using like cat first file n then copy it to second?

  2. echo “hello” | tee -a

  3. echo “hello” | tee -a file1 file2
    or
    echo “hello” | tee -a file1 file2 > /dev/null

  4. I was looking for a way how to look at some php script output on screen but also to have whole output saved in a file. Your post is exactly what I needed. Great thanks for sharing this with us. :)

  5. [...] se dešava, umesto da mi ceo izlaz stoji u nekom tamo log fajlu. No, zahvaljući unix tee komandi i ovom postu, danas sam naučio da mogu imati [...]

  6. Thanks! I spent hours looking for just this!

Leave a Reply

Security Code: