Tuesday, March 11, 2008

Redirecting stdout and stderr

Typing commands in shell will result in two output streams namely stdout and stderr. Stdout is the normal output stream while stderr is the output stream for error. For example, if you type the below command,

# ls /usr/ /user
ls: cannot access /user: No such file or directory
/usr/:
bin games java lib local share tmp
etc include kerberos libexec sbin src

The blue line is the stderr and the green lines are the stdout. By default, all output will be directed to the screen, but you can redirect both stdout and stderr to a file.
To redirect stdout to a file named /tmp/stdout and display the stderr to the screen:

# ls /usr /user > /tmp/stdout
ls: cannot access /user: No such file or directory

To redirect stderr to a file named /tmp/stderr and display stdout to the screen:

# ls /usr /user 2> /tmp/stderr
/usr:
bin games java lib local share tmp
etc include kerberos libexec sbin src

To redirect both to the file named /tmp/all:

# ls /usr /user > /tmp/all 2>&1

or

# ls /usr /user &> /tmp/all

To append the stderr and stdout to a file, simply:

# ls /usr /user >> /tmp/all 2>&1

To both redirect and display the stderr and stdout, use tee:

# ls /usr /user 2>&1 | tee /tmp/all
ls: cannot access /user: No such file or directory
/usr:
bin
etc
games
include
java
kerberos
lib
libexec
local
sbin
share
src
tmp

Instead of redirecting to a file or display, you can also redirect them to other command. For example, if you want to email your stderr and stdout to root user of the local machine(Make sure your mta service is on, if not the message will not be delivered):

# ls /usr /user 2>&1 | mail root@localhost

If you do not want to see any error display, just redirect the stderr to /dev/null

# ls /user 2> /dev/null

3 comments:

sjoshi said...

Thanks this is a great post and be very helpful when creating scripts. I have another question, how do I redirect the stdout and stderr when running a script. Lets say I want to run a script and all the output and error from the script needs to be written to a file. How would I accomplish that... thanks for your help

Shelby Zhu said...

Can you enclose the whole script in curly brackets and redirect it?

Shelby Zhu said...

You may enclose the whole script (or the section your want to redirect) in curly bracket and redirect it.