Standard Error and Standard Out
November 2nd, 2006
Prereqs: Standard error and out are file descriptors. Standard error is output from a command, which is different than standard output.
In this entry, I am going to describe how to mix standard error and standard out. That is, how to send them to the same different places. Below, I create a file called this_file_exists and use this_file_does_not_exist as a filename of a file which does not exist. As you can see below, ‘>ls.out 2>ls.err` sends standard out to ls.out and standard error to ls.err.
root@www:~ # touch this_file_exists
root@www:~ # ls -l this_file_exists this_file_does_not_exist
ls: this_file_does_not_exist: No such file or directory
-rw-r--r-- 1 root root 0 Nov 2 07:38 this_file_exists
root@www:~ # ls -l this_file_exists this_file_does_not_exist >ls.out 2>ls.err
root@www:~ # cat ls.out
-rw-r--r-- 1 root root 0 Nov 2 07:38 this_file_exists
root@www:~ # cat ls.err
ls: this_file_does_not_exist: No such file or directory
Alternatively, you can send both stderr and stdout to the same file using >ls.out 2>&1
root@www:~ # ls -l this_file_exists this_file_does_not_exist >ls.out 2>&1
root@www:~ # cat ls.out
ls: this_file_does_not_exist: No such file or directory
-rw-r--r-- 1 root root 0 Nov 2 07:38 this_file_exists
root@www:~ #
Or if you are constructing a pipeline, you can send standard error along for the ride:
root@www:~ # ls -l this_file_exists this_file_does_not_exist 2>&1 | grep -v 'No such file'
-rw-r--r-- 1 root root 0 Nov 2 07:38 this_file_exists
Without, ‘2>&1`, this is what would be displayed:
root@www:~ # ls -l this_file_exists this_file_does_not_exist | grep -v 'No such file'
ls: this_file_does_not_exist: No such file or directory
-rw-r--r-- 1 root root 0 Nov 2 07:38 this_file_exists
That was for instructional purposes. A better way would be to send standard error to /dev/null:
root@www:~ # ls -l this_file_exists this_file_does_not_exist 2>/dev/null
-rw-r--r-- 1 root root 0 Nov 2 07:38 this_file_exists
The following example, uses the exist status of ls, by sending both the standard output and error to /dev/null.
root@www:~ # rm ls.out
(Make sure ls.out does not exist, for the example below.)
root@www:~ # OUTFILE=false; if ls *.out >/dev/null 2>&1; then OUTFILE=true; fi
root@www:~ # echo $OUTFILE
false
root@www:~ # touch ls.err
(Make sure ls.err exists, for the example below.)
root@www:~ # ERRFILE=false; if ls *.err >/dev/null 2>&1; then ERRFILE=true; fi
root@www:~ # echo $ERRFILE
true


Leave a Reply