Open main menu

CDOT Wiki β

BASH Exit Status

Revision as of 22:07, 15 September 2008 by Chris Tyler (talk | contribs) (Exit Codes and Flow Control)

Exist Status

Each process that executes on a Linux system leaves a whole number exit code (or exit status, result code, or error code) when it terminates.

The value of the exit code is usually 0 if no errors were encountered, or non-zero if an error was encountered. The meaning of specific codes varies program-by-program; see the documentation (such as the man page) for a program to determine the meaning of those codes.

In a multi-command pipeline, the exit status of the last command is used as the exit status for the entire pipeline. (In BASH documentation, the term pipeline is used to refer to any single command or sequence of commands; see the BASH manpage for details).

Retrieving Exist Status

BASH places the exit status of the most recently-executed pipeline in the special variable $?. You can view the value of this variable using the echo command:

$ ls /tmp >/dev/null
$ echo $?
0
$ ls /temp >/dev/null
ls: cannot access /temp: No such file or directory
$ echo $?
2

Setting the Exit Status when Exiting from a Shell Script

The BASH exit command can be used with a whole-number numeric positional argument to exit a script with a particular status code. For example:

exit 2

Will exit the script with an exit code of 2.

Exit Codes and Flow Control

Exit codes are used extensively with the BASH Flow Control operators.