How to redirect output to a file as well as display it out
December 6th, 2007 mysurface Posted in Text Manipulation, pipeline, python, tee | Hits: 67795 |
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?
Live Chat!







December 13th, 2007 at 3:12 pm
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?
October 21st, 2008 at 12:48 am
echo “hello” | tee -a
October 21st, 2008 at 12:49 am
echo “hello” | tee -a file1 file2
or
echo “hello” | tee -a file1 file2 > /dev/null
November 19th, 2008 at 12:23 am
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. :)
November 19th, 2008 at 12:47 am
[...] 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 [...]
April 18th, 2009 at 12:30 pm
Thanks! I spent hours looking for just this!
August 17th, 2009 at 7:12 pm
Very useful to me
Thanks
October 7th, 2009 at 8:51 pm
Thanks - the redirect stderr/stdout to a file AND console is what I needed. Appreciate the post.
December 4th, 2009 at 4:08 pm
Thanx mate !
January 15th, 2010 at 11:23 am
hi, what if i want out both stdout&stderr to file1 and stderr to file2 ? is it possible to do that?
February 3rd, 2010 at 8:55 am
Nice post, bravo!
March 3rd, 2010 at 11:37 pm
Have you ever piped output through firefox to a file? Would use lynx but its an unsupported browser for the webpage I’m trying to copy down.