UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 44.6 Pattern Matching in case Statements Chapter 44
Shell Programming for the Uninitiated
Next: 44.8 Test Exit Status with the if Statement
 

44.7 Exit Status of UNIX Processes

When a UNIX process (command) runs, it can return a numeric status value to the process that called (started) it. The status can tell the calling process whether the command succeeded or failed. Many (but not all) UNIX commands return a status of zero if everything was okay or non-zero (1, 2, etc.) if something went wrong. A few commands, like grep and diff, return a different non-zero status for different kinds of problems; see your online manual pages to find out.

The Bourne shell puts the exit status of the previous command in the question mark (?) variable. You can get its value by preceding it with a dollar sign ($), just like any other shell variable. For example, when cp copies a file, it sets the status to 0. If something goes wrong, cp sets the status to 1:

$ cp afile /tmp
$ echo $?

$ cp afiel /tmp
cp: afiel: No such file or directory
$ echo $?
1

In the C shell, use the status variable instead:

% cp afiel /tmp
cp: afiel: No such file or directory
% echo $status
1

Of course, you usually don't have to display the exit status in this way, because there are several ways (44.8, 44.9, 44.10) to use the exit status of one command as a condition of further execution.

true
false
Two simple UNIX utilities do nothing but return an exit status. true returns a status of 0 (zero); false returns 1 (one). There are GNU versions on the CD-ROM-and no, they don't have any amazing extra features. ;-)

The exit status of pipelines (1.4) is the status of the last command in the pipeline. [2] You can't test the exit status of a background job in the Bourne shell unless you use the wait command to wait for it (in effect, to bring the job out of the background).

[2] I've seen a few places where that wasn't true - in an early Korn Shell, I think, and a couple of other places too - but that was a long time ago.

- JP


Previous: 44.6 Pattern Matching in case Statements UNIX Power ToolsNext: 44.8 Test Exit Status with the if Statement
44.6 Pattern Matching in case Statements Book Index44.8 Test Exit Status with the if Statement

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System