Seperating STDOUT and STDERR

From assela Pathirana

Jump to: navigation, search

The commands on this page can be tried out on Cygwin installed in a windows PC or on any UNIX computer.

This example is written for Bash shell environment. It may not work in a differnt shell like csh.

Consider the follwing situation:
ls * i-am-not-here-for-sure
* indicates all the files in the current folder. Let's assume that you don't have a file named i-am-not-here-for-sure (that is unless you are crazy!), then the first argument of ls function generates a list of files and directories as output. Second one generates an error:

$ ls * Sample-rainfall myfirstscript.bash tmp monthly-total.bash myfirstscript.txt tmp.bash

$ ls i-am-not-here-for-sure ls: i-am-not-here-for-sure: No such file or directory

The two together:
$ ls * i-am-not-here-for-sure
ls: i-am-not-here-for-sure: No such file or directory
Sample-rainfall     myfirstscript.bash  out  tmp.bash
monthly-total.bash  myfirstscript.txt   tmp

Now, on the terminal, the error message and the output looks similar; but they came here by very differnt paths! Let's demonstrate this by selectively filtering the streams:

  1. First let's redirect the STDOUT to a file</nowiki>

$ ls * i-am-not-here-for-sure > out ls: i-am-not-here-for-sure: No such file or directory

only the error message (STDERR stream) shows on the terminal.
  1. Redirecting STDERR to a file</nowiki>

$ ls * i-am-not-here-for-sure 2> out Sample-rainfall myfirstscript.bash out tmp.bash monthly-total.bash myfirstscript.txt tmp

only the results (STDOUT stream) is on the terminal.
  1. Redirect STDERR to STDOUT and then write STDOUT to a file</nowiki>

$ ls * i-am-not-here-for-sure > out 2>&1

No output!

Don't forget to also check the content of the file out each time.

Personal tools