Using Exit Status

[previous] [next] [table of contents] [index]

When a UNIX command runs, it can return a numeric status value to the program that started it. The status can tell the calling program whether the command succeeded or failed. Many (but not all) UNIX commands return a status of zero if everything was okay or nonzero (1, 2, etc.) if something went wrong. Almost all MH programs return a status. The Bourne shell puts the exit status of each process it runs into its question mark (?) variable; the C shell uses its status variable. So, to see the exit status of an MH command in a particular situation, run the MH command -- then type echo $? to the Bourne shell or echo $status to the C shell.

Of course, you usually don't have to display the exit status in this way, because the Bourne shell provides a couple of ways to use the exit status of one command as a condition of further execution. After a shell program runs a UNIX command, it can test the exit status to see if there was a problem.

Here's a simple example: a Bourne shell script called newmsgs. It uses the shell's if structure to run inc, then test inc's exit status and branch. If inc brings in some messages, newmsgs runs the show command to show the current message (the first new message). Otherwise, the program prints a note that there were no messages to show. (You can also get this simple script from this book's online archive. It's at download/split/mh/bin/newmsgs.)

% cat newmsgs
#! /bin/sh
if inc
    echo "Sorry; no new message to show now."
A more UNIX-like shell script wouldn't tell you that there were no messages; the no mail to incorporate message from inc would be enough. You could rewrite newmsgs to use the shell's && operator:
#! /bin/sh
inc && show
There's more information about && in the Section Making Aliases and Functions. The shells also have a || operator that runs the second command if the first command returns a nonzero status.

[Table of Contents] [Index] [Previous: Shell Command Substitution] [Next: Looping Through a List of Arguments]

Revised by Jerry Peek. Last change $Date: 1999/10/10 05:14:05 $

This file is from the third edition of the book MH & xmh: Email for Users & Programmers, ISBN 1-56592-093-7, by Jerry Peek. Copyright © 1991, 1992, 1995 by O'Reilly & Associates, Inc. This file is freely available; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. For more information, see the file copying.htm.

Suggestions are welcome: Jerry Peek <>