Exit Statuses

Every command—be it built-in, shell function, or external—when it exits, returns a small integer value to the program that invoked it. This is known as the program's exit status. There are a number of ways to use a program's exit status when programming with the shell.

Exit Status Values

By convention, an exit status of 0 indicates "success"; i.e., that the program ran and didn't encounter any problems. Any other exit status indicates failure.[1] (We'll show you shortly how to use the exit status.) The built-in variable ? (accessed as $?) contains the exit value of the last program that the shell ran.

For example, when you type ls, the shell finds and runs the ls program. When ls finishes, the shell recovers ls's exit status. Here's an example:

$ ls -l /dev/null                                      
               ls on an existing file
crw-rw-rw-  1 root  root  1, 3 Aug 30 2001 /dev/null   ls's output
$ echo $?                                              
               Show exit status
0                                                      Exit status was successful
$ ls foo                                               
               Now ls a nonexistent file
ls: foo: No such file or directory                     ls's error message
$ echo $?                                              
               Show exit status
1                                                      Exit status indicates failure

The POSIX standard defines the exit statuses and their meanings, as shown in Table 6-5.

Table 6-5. POSIX exit statuses

Value

Meaning

0

Command exited successfully.

> 0

Failure during redirection or word expansion (tilde, variable, command, and arithmetic expansions, as well as word splitting).

1-125

Command exited unsuccessfully. The meanings of particular exit values are defined by each individual command.

126

Command found, but ...

Get Classic Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.