Chapter 3. Tutorial / Reference

 

...there are dark corners in the Bourne shell, and people use all of them.

 Chet Ramey

3.1. exit and exit status

The exit command may be used to terminate a script, just as in a C program. It can also return a value, which is available to the shell.

Every command returns an exit status (sometimes referred to as a return status ). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually may be interpreted as an error code.

Likewise, functions within a script and the script itself return an exit status. The last command executed in the function or script determines the exit status. Within a script, an exit nn command may be used to deliver an nn exit status to the shell (nn must be a decimal number in the 0 - 255 range).

$? reads the exit status of script or function.


Example 3-1. exit / exit status

   1 #!/bin/bash
   2 
   3 echo hello
   4 echo $?
   5 # exit status 0 returned
   6 # because command successful.
   7 
   8 lskdf
   9 # bad command
  10 echo $?
  11 # non-zero exit status returned.
  12 
  13 echo
  14 
  15 exit 143
  16 # Will return 143 to shell.
  17 # To verify this, type $? after script terminates.
  18 
  19 # By convention, an 'exit 0' shows success,
  20 # while a non-zero exit value indicates an error or anomalous condition.
  21 
  22 # It is also appropriate for the script to use the exit status
  23 # to communicate with other processes, as when in a pipe with other scripts.