Home > Bash, Linux, Programmering > Loggning i Linux

Loggning i Linux

September 13th, 2010 Leave a comment Go to comments

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

Ref: http://linux.byexamples.com/archives/349/how-to-redirect-output-to-a-file-as-well-as-display-it-out/

Categories: Bash, Linux, Programmering Tags:
  1. No comments yet.
  1. No trackbacks yet.