Programming with the UNIX system shell

Return codes

Most shell commands issue return codes that show whether the command executed properly. By convention, if the value returned is 0 (zero), then the command executed properly; any other value shows that it did not. The return code is not printed automatically, but is available as the value of the shell special parameter ``$?''.

Checking return codes

After executing a command interactively, you can see its return code by typing

   echo $?
Consider the following example:
   $ cat hi
   This is file hi.
   $ echo $?
   $ cat hello
   cat: cannot open hello
   $ echo $?
In the first case, the file hi exists in your directory and has read permission for you. The cat command behaves as expected and outputs the contents of the file. It exits with a return code of 0, which you can see using the parameter $?. In the second case, the file either does not exist or does not have read permission for you. The cat command prints a diagnostic message and exits with a return code of 2.

Using return codes with the exit command

A shell program normally terminates when the last command in the file is executed. However, you can use the exit command to terminate a program at some other point. Perhaps more importantly, you can also use the exit command to issue return codes for a shell program.

Next topic: Loop constructs: for and while
Previous topic: Using ed in a shell program

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004