From LQWiki
Jump to: navigation, search

stderr is the standard error stream, used for reporting error messages. Standard error messages are usually reported to the terminal (though, like the other streams, they can be logged to a file), and are kept seperate from standard output.

Why is this so? Consider the case where a program in the middle of a pipeline fails and there is no standard error stream. If it logs an error, without stderr it must report it to stdout, but the user then never sees this error message since stdout of that program is piped to stdin of the next. This can also mean that irrelevant data is being piped to a program which may not be able to handle it, or it will create erroneous output based on erroneous input (the concept of garbage in, garbage out).

Worth noting is that stderr is unbuffered, that means that things written to stderr is shown immediately. Stdout is, however, buffered which imples that things written to stdout are printed to the user when either a newline is written or the buffer contains enough characters.

In order to distinguish properly stdout from stderr, when using piping, stderr is not connected to the next program in the pipeline. However, it may be necessary for the output of stderr to go somewhere else, such as an error log file, or to the null device to discard the message. They are piped using the & modifier, for example:

someprogram |& someotherprogram 
someprogram >& somefile

You can redirect stderr to whereever you want using 2>:

duffman:~ # ls a
/bin/ls: a: No such file or directory
duffman:~ # ls a 2>/dev/null
duffman:~ #

Note that

  • 0 stands for stdin
  • 1 stands for stdout
  • 2 stands for stderr

The redirection 2>/dev/null sends stderr (the error message "No such file or directory") to /dev/null.

You can also redirect stderr to send to the same stream as stdout

duffman:~ # ls text a
/bin/ls: a: No such file or directory
duffman:~ # ls a 1>/dev/null
/bin/ls: a: No such file or directory
duffman:~ # ls text 1>/dev/null
duffman:~ # ls text a 2>&1 | wc -l
duffman:~ #         

You see here that the file a does not exist and ls a produces an error message. The file text exists and ls text produces output to stdout. ls a produces one line of output to stderr, ls text produces one line of output to stdout. ls text a produces one line output to stdout and one to stderr. ls text a 2>&1 unites both outputs to one stream, stdout. This can be counted with wc.

See also