Exit with status zero only on success
On UNIX systems, programs set an integer when they terminate that is called exit status. The importance of the exit status is as follows:
The UNIX ecosystem relies on the exit status to be zero if and only if the program executed successfully.
The exit status is used by
- shell scripts to determine which branch to take in a conditional statement,
- shell scripts to detect errors when
set -e
was executed beforehand, - build tools like
make
andninja
to detect errors of the programs they are calling (e.g., to detect compiler and linker errors), - continuous integration and test software (like
ctest
) do detect failing tests.
Everything else (e.g., printing "ERROR") is irrelevant from the point of view of scripting. Ignoring the rule above can lead to real problems; it will lead to problems during testing, see #53 (closed) for an example.
The exit status must be in the range 0-255. Values outside of this range will be taken modulo 256, see POSIX: exit, _Exit, _exit - terminate a process. Additionally, some values are reserved, cf. Advanced Bash Scripting Guide: Appendix E. Exit Codes With Special Meanings. With a careful choice of the exit status, it is possible to allow scripting involving failing programs. For example, the grep
manpage has to say the following about the exit status:
EXIT STATUS
Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the
-q
or--quiet
or--silent
is used and a line is selected, the exit status is 0 even if an error occurred.
As a rule of thumb, return 0 only on success and 1 otherwise. If the program crashes, then the shell takes care of setting a nonzero exit status.
The table below lists ways to set the exit status in various languages.
Language | Code | Exit status | Description |
---|---|---|---|
C/C++ | int main() {} |
0 | Requires C99 or newer; requires C++98(?) or newer |
C/C++ | int main() { return x; } |
x |
|
C | #include <stdlib.h> ... int main() { return EXIT_SUCCESS; } |
0 | |
C | #include <stdlib.h> ... int main() { return EXIT_FAILURE; } |
Nonzero | |
C | #include <stdlib.h> ... exit(x); |
x |
See also _exit , _Exit
|
C++ | #include <cstdlib> ... std::exit(x); |
x |
|
Python | (not set explicitly) | 0 if there was no error, 1 otherwise | |
Python | import sys; sys.exit() |
0 | |
Python | import sys; sys.exit(1) |
1 | |
Python | import sys; sys.exit("error message") |
1 | Argument printed to stderr
|
Shell script | exit |
0 | |
Shell script | exit x |
x |
|
Fortran | STOP |
0 | |
Fortran | STOP x |
x |