Standard Error Basics

April 27th, 2006

Ok, so we know what stdin and stdout are. We also know that a pipe can send stdout from one command to another command as stdin. Using grep we can pull out a specific line in stdin using a search term. Summarized as follows:

root@www:~ # echo brock
brock
root@www:~ # echo sarah
sarah
root@www:~ # echo brock; echo sarah
brock
sarah
root@www:~ # echo brock; echo sarah | grep brock
brock

However, there is another file descriptor. Its called Standard Error or stderr. Stderr is the exact same thing is stdout, except its used for errors. Lets say we are using ls to list files in a directory (ls is similar to dir on windows). We have a file named a_file. Here are we going to use > instead of a pipe, this will concatenate the output to a file instead. Quickly recapping we can use to send stdout to another command and > to send stdout to a file.

Here are first simply list the file and then we take the output of listing the file and send it to a file name ls.out. We then use the cat command to simply display the contents of ls.out (similar to type on Windows).

root@www:~ # ls -l a_file
-rw-r--r-- 1 root root 0 Mar 9 20:42 a_file
root@www:~ # ls -l a_file > ls.out
root@www:~ # cat ls.out
-rw-r--r-- 1 root root 0 Mar 9 20:42 a_file
root@www:~ #
root@www:~ # rm ls.out
(Make sure you remove ls.out or you.ll be confused later.)

That is fine and dandy. What happens if a_file does not exist.

root@www:~ # ls -l not_a_file
ls: not_a_file: No such file or directory
root@www:~ # ls -l not_a_file > ls.out
ls: not_a_file: No such file or directory
root@www:~ # cat ls.out
root@www:~ #
root@www:~ # rm ls.out

A few things to note here:

ls.out was empty

When we redirected stdout to ls.out, the following was displayed on screen “ls: not_a_file: No such file or directory” The reason is that “ls: not_a_file: No such file or directory” is not coming from the stdout of ls -l not_a_file, its coming from stderr. Interesting. Now lets place a 2 in from of the > redirector.

root@www:~ # ls -l not_a_file
ls: not_a_file: No such file or directory
root@www:~ # ls -l not_a_file 2> ls.out
root@www:~ # cat ls.out
ls: not_a_file: No such file or directory
root@www:~ #
root@www:~ # rm ls.out

Here ls.out did contain the output of ls -l not_a_file because we told bash to redirect stderr (file descriptor 2) to the file. In this case, stderr was redirected to a file.

Please read Standard Error and Standard Out on how to mix out and error.

Leave a Reply

If Wordpress eats your comment (shell output, loops, ex..) brock (at) gmail dot com.