Status, STDERR and STDOUT

The problem: Consider the behavior of the command `ls filename` when filename exists and when it doesn't:

$ls references
references
$ls pickles
ls: pickles: No such file or directory 

If we wish to know if a file exists, before we begin probing its contents, then we might be tempted to try using a=`ls filename`, perhaps followed with `echo $?` (the status of the last executed command) to examine the system's response. However, as shown in the following, error messages are, by default directed to a different place (known as STDERR), than the standard output (known as STDOUT) that comes to the screen.

$a=`ls pickles`
ls: pickles: No such file or directory
$echo $?
1
$echo $a 

Note that a) the output goes to the screen, rather than the variable $a, even though the status of the command shows $?=1, meaning that the ls command terminated unsuccessfully.

How, then might we resolve this problem? We redirect STDERR to STDOUT such that it, also, may be trapped in the variable a:

$a=`ls references 2>&1`
$echo $?
0
$echo $a
references
$a=`ls pickles 2>&1`
$echo $?
1
$echo $a
ls: pickles: No such file or directory 

The expression 2>&1 redirects STDERR (associated with filehandle 2) to STDOUT (associated with filehandle 1).

Oftentimes, in cgi scripting, this is not an issue since error messages do not appear in the cgi stream your script constructs, but it may prove simplest to identify and then to explicitly ignore "anomalies" before they become problematic.

What is STDIN (&0)? The stuff sent to a command through a pipe.


The status flag for a few useful commands:

grep   wc, ls and the like
$cat anyfile
match
$cat nofile
cat: nofile: No such file
Two filenames: one file exists, the other doesn't.
$wc anyfile
  1   1   6 anyfile
$echo $?
0

 

$grep match anyfile
match
$echo $?
0
When grep finds a match $? is 0.
$grep nomatch anyfile
$echo $?
1
When grep does not find a match in an existing file, $? is 1.
$wc nof
wc:nof: No such file
$echo $?
1 

 

$grep match nofile
grep:nofile: No such file
$echo $?
2
When the file doesn't exist, $? is 2.
$grep -s match nofile
$echo $?
1 
The -s flag on grep allows suppression of error messages.