Using Exit Status

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 examples/mh/bin/newmsgs.)

    % cat newmsgs
    #! /bin/sh
    if inc
    then
        show
    else
        echo "Sorry; no new message to show now."
    fi
    
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.