323

A process is considered to have completed correctly in Linux if its exit status was 0.

I've seen that segmentation faults often result in an exit status of 11, though I don't know if this is simply the convention where I work (the apps that failed like that have all been internal) or a standard.

Are there standard exit codes for processes in Linux?

codeforester
  • 28,846
  • 11
  • 78
  • 104
Nathan Fellman
  • 108,984
  • 95
  • 246
  • 308
  • 6
    if you're looking for the thing called "system error number" returned by system functions look here at [errno](http://stackoverflow.com/questions/503878/how-to-know-what-the-errno-means) – marinara Oct 21 '12 at 17:56

10 Answers10

348

Part 1: Advanced Bash Scripting Guide

As always, the Advanced Bash Scripting Guide has great information: (This was linked in another answer, but to a non-canonical URL.)

1: Catchall for general errors
2: Misuse of shell builtins (according to Bash documentation)
126: Command invoked cannot execute
127: "command not found"
128: Invalid argument to exit
128+n: Fatal error signal "n"
255: Exit status out of range (exit takes only integer args in the range 0 - 255)

Part 2: sysexits.h

The ABSG references sysexits.h.

On Linux:

$ find /usr -name sysexits.h
/usr/include/sysexits.h
$ cat /usr/include/sysexits.h

/*
 * Copyright (c) 1987, 1993
 *  The Regents of the University of California.  All rights reserved.

 (A whole bunch of text left out.)

#define EX_OK           0       /* successful termination */
#define EX__BASE        64      /* base value for error messages */
#define EX_USAGE        64      /* command line usage error */
#define EX_DATAERR      65      /* data format error */
#define EX_NOINPUT      66      /* cannot open input */    
#define EX_NOUSER       67      /* addressee unknown */    
#define EX_NOHOST       68      /* host name unknown */
#define EX_UNAVAILABLE  69      /* service unavailable */
#define EX_SOFTWARE     70      /* internal software error */
#define EX_OSERR        71      /* system error (e.g., can't fork) */
#define EX_OSFILE       72      /* critical OS file missing */
#define EX_CANTCREAT    73      /* can't create (user) output file */
#define EX_IOERR        74      /* input/output error */
#define EX_TEMPFAIL     75      /* temp failure; user is invited to retry */
#define EX_PROTOCOL     76      /* remote error in protocol */
#define EX_NOPERM       77      /* permission denied */
#define EX_CONFIG       78      /* configuration error */

#define EX__MAX 78      /* maximum listed value */
IQAndreas
  • 7,014
  • 4
  • 36
  • 63
Schof
  • 5,815
  • 5
  • 25
  • 34
  • 5
    Note that in some flavors of unix, some commands use an exit status of 2 to indicate other things. For instance, many implementations of grep use an exit status of 2 to indicate an error, and use an exit status of 1 to mean that no selected lines were found. – NamshubWriter Oct 25 '12 at 17:06
  • 3
    On BSDs there's a man page summarising the info from sysexits.h: `man sysexits` – georgebrock Jul 29 '13 at 09:38
  • 7
    What @NamshubWriter said. [Exit status 2](http://stackoverflow.com/a/40484670/699305) is the universal go-to for incorrect command line usage in Unix utilities, not just in "some flavors of unix" but in general. The header shown in this answer does not reflect actual conventions, now or when it was written in 1987. – alexis May 08 '17 at 09:16
  • The ABS is not "great". Please read up on the subject; it's not exactly hard to find criticisms. – tripleee Nov 30 '19 at 09:05
  • But where is the actual official source code for `sysexits.h`? The [man page](https://www.freebsd.org/cgi/man.cgi?query=sysexits) everybody keeps referencing is just prose. For example it references `EX_OK` but doesn't actually define it in a normative way like the other codes. Are there more that are missing? – Garret Wilson Dec 11 '19 at 16:31
90

8 bits of the return code and 8 bits of the number of the killing signal are mixed into a single value on the return from wait(2) & co..

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>

int main() {
    int status;

    pid_t child = fork();
    if (child <= 0)
        exit(42);
    waitpid(child, &status, 0);
    if (WIFEXITED(status))
        printf("first child exited with %u\n", WEXITSTATUS(status));
    /* prints: "first child exited with 42" */

    child = fork();
    if (child <= 0)
        kill(getpid(), SIGSEGV);
    waitpid(child, &status, 0);
    if (WIFSIGNALED(status))
        printf("second child died with %u\n", WTERMSIG(status));
    /* prints: "second child died with 11" */
}

How are you determining the exit status? Traditionally, the shell only stores an 8-bit return code, but sets the high bit if the process was abnormally terminated.

$ sh -c 'exit 42'; echo $?
42
$ sh -c 'kill -SEGV $$'; echo $?
Segmentation fault
139
$ expr 139 - 128
11

If you're seeing anything other than this, then the program probably has a SIGSEGV signal handler which then calls exit normally, so it isn't actually getting killed by the signal. (Programs can chose to handle any signals aside from SIGKILL and SIGSTOP.)

Betlista
  • 9,561
  • 10
  • 62
  • 99
ephemient
  • 180,829
  • 34
  • 259
  • 378
  • 10
    Given the way the question now appears, this does not appear to be the most useful (and thus accepted) answer. – David J. Dec 09 '13 at 22:49
73

'1' >>> Catchall for general errors

'2' >>> Misuse of shell builtins (according to Bash documentation)

'126'>>> Command invoked cannot execute

'127'>>>"command not found"

'128'>>> Invalid argument to exit

'128+n'>>>Fatal error signal "n"

'130'>>> Script terminated by Control-C

'255'>>>Exit status out of range

This is for bash. However, for other applications, there are different exit codes.

v8-E
  • 897
  • 2
  • 14
  • 19
segfault
  • 5,333
  • 8
  • 42
  • 62
  • 1
    It look like you both answered in the same minute. Tian would have to be pretty quick to see your links and paste them in. – Nathan Fellman Jul 09 '09 at 05:37
  • 6
    Note that 'control-C yields 130' is consistent with '128+n' for signal n; control-C generates SIGINT which is signal 2. – Jonathan Leffler Sep 03 '11 at 18:44
  • 3
    This seems to be plagiarized from the ABS without attribution. (We can tell because the ABS contains incorrect or at least misleading information.) – tripleee Oct 10 '16 at 08:43
  • 5
    These are RESERVED exit codes, according the [Advanced Bash-Scripting Guide](http://www.tldp.org/LDP/abs/html/exitcodes.html). That means these values _should therefore be avoided for user-specified exit parameters_. – ingyhere Jan 09 '17 at 20:14
65

None of the older answers describe exit status 2 correctly. Contrary to what they claim, status 2 is what your command line utilities actually return when called improperly. (Yes, an answer can be nine years old, have hundreds of upvotes, and still be wrong.)

Here is the real, long-standing exit status convention for normal termination, i.e. not by signal:

  • Exit status 0: success
  • Exit status 1: "failure", as defined by the program
  • Exit status 2: command line usage error

For example, diff returns 0 if the files it compares are identical, and 1 if they differ. By long-standing convention, unix programs return exit status 2 when called incorrectly (unknown options, wrong number of arguments, etc.) For example, diff -N, grep -Y or diff a b c will all result in $? being set to 2. This is and has been the practice since the early days of Unix in the 1970s.

The accepted answer explains what happens when a command is terminated by a signal. In brief, termination due to an uncaught signal results in exit status 128+[<signal number>. E.g., termination by SIGINT (signal 2) results in exit status 130.

Notes

  1. Several answers define exit status 2 as "Misuse of bash builtins". This applies only when bash (or a bash script) exits with status 2. Consider it a special case of incorrect usage error.

  2. In sysexits.h, mentioned in the most popular answer, exit status EX_USAGE ("command line usage error") is defined to be 64. But this does not reflect reality: I am not aware of any common Unix utility that returns 64 on incorrect invocation (examples welcome). Careful reading of the source code reveals that sysexits.h is aspirational, rather than a reflection of true usage:

     *    This include file attempts to categorize possible error
     *    exit statuses for system programs, notably delivermail
     *    and the Berkeley network.
    
     *    Error numbers begin at EX__BASE [64] to reduce the possibility of 
     *    clashing with oth­er exit statuses that random programs may 
     *    already return. 
    

    In other words, these definitions do not reflect the common practice at the time (1993) but were intentionally incompatible with it. More's the pity.

alexis
  • 43,587
  • 14
  • 86
  • 141
  • What should a program return when it *does* handle termination by catching SIGINT/Ctrl-C? Still 130? Does use of another shell besides bash matter? – Gringo Suave Jul 20 '18 at 17:50
  • 1
    The shell that is executing the program is irrelevant; a process could theoretically choose to exit with different status depending on its parent process, but I've never, ever heard of a case where this happens. – alexis Jul 24 '18 at 14:22
  • 1
    If a program catches SIGINT, cleans up, and exits anyway, the status is whatever makes sense for the program. For example, `more` will reset the terminal modes and exit with status 0 (you can try it). – alexis Jul 24 '18 at 14:23
  • 1
    This answer implies a much higher grade of standardization than what is actually the case. There is no proper standardization of the meaning of the value 2, and actual practice is then predictably very mixed. It is true that many tools return 2 for improper usage but it's not exactly well-defined what "improper usage" means, and many others do not adhere to this convention. – tripleee Nov 30 '19 at 09:02
  • @tripleee "tools" is not well-defined either! :-) Sure, anyone can write a command-line program and it can return anything at all, but the old-school "Unix command-line utilities" that have been around longer than Linux, or the contents of GNU coreutils, are quite consistent on this. If you think otherwise, please name some tools in this group that don't use status 2 this way. Also, "improper usage" is your term (and I agree it's a vague term); I wrote "command line usage error", which is pretty specific: non-existent or incompatible options, wrong number of non-option arguments, etc. – alexis Dec 03 '19 at 21:07
  • Not very compelling, but [Heirloom `diff`](http://heirloom.sourceforge.net/man/diff.1.html) says "2 for trouble" (sic). I'll keep looking and will get back to you when I have some examples. – tripleee Dec 04 '19 at 05:37
  • Yeah that's a bit elliptical :'-). But this example is entirely consistent with what I'm saying: In context, "trouble" here clearly means "diff cannot run" (and therefore cannot decide whether or not there are differences). And "trouble" with normal termination generally translates to invalid flags, file not found, or whatever the matter is that prevents diff from running. – alexis Dec 04 '19 at 13:09
  • And indeed, check the source code: https://github.com/kallisti5/heirloom/blob/master/diff/diff.c . Exit status 2 when the program fails (flag errors but also files too large). – alexis Dec 04 '19 at 13:16
  • You claim that the highly voted answer is wrong yet at the same time could only provide a convention. – konsolebox Dec 13 '19 at 10:46
  • @konsolebox, what did you expect? There is no standard, the convention is precisely what we've got. `sysexits.h` was and is purely aspirational. – alexis Dec 16 '19 at 08:14
  • @alexis So what's wrong about the other answer again? Take note the the question is **"Are there any standard exit status codes in Linux?"**. Taking that into account your answer is actually the one that's invalid. – konsolebox Dec 18 '19 at 14:26
  • @alexis `sysexits.h` is a widely used definition and is almost synonymous to a standard. At the very least it's a stronger "standard" than the convention you mentioned. It still doesn't make sense how you could just blatantly describe it as wrong. – konsolebox Dec 18 '19 at 14:37
  • Um, if you know of any standand Unix utilities that follow this "widely used definition", please list them here. – alexis Dec 18 '19 at 23:07
25

There are no standard exit codes, aside from 0 meaning success. Non-zero doesn't necessarily mean failure either.

stdlib.h does define EXIT_FAILURE as 1 and EXIT_SUCCESS as 0, but that's about it.

The 11 on segfault is interesting, as 11 is the signal number that the kernel uses to kill the process in the event of a segfault. There is likely some mechanism, either in the kernel or in the shell, that translates that into the exit code.

Chris Arguin
  • 11,370
  • 4
  • 30
  • 46
22

sysexits.h has a list of standard exit codes. It seems to date back to at least 1993 and some big projects like Postfix use it, so I imagine it's the way to go.

From the OpenBSD man page:

According to style(9), it is not good practice to call exit(3) with arbi- trary values to indicate a failure condition when ending a program. In- stead, the pre-defined exit codes from sysexits should be used, so the caller of the process can get a rough estimation about the failure class without looking up the source code.
9

To a first approximation, 0 is success, non-zero is failure, with 1 being general failure, and anything larger than one being a specific failure. Aside from the trivial exceptions of false and test, which are both designed to give 1 for success, there's a few other exceptions I found.

More realistically, 0 means success or maybe failure, 1 means general failure or maybe success, 2 means general failure if 1 and 0 are both used for success, but maybe sucess as well.

The diff command gives 0 if files compared are identical, 1 if they differ, and 2 if binaries are different. 2 also means failure. The less command gives 1 for failure unless you fail to supply an argument, in which case, it exits 0 despite failing.

The more command and the spell command give 1 for failure, unless the failure is a result of permission denied, nonexistent file, or attempt to read a directory. In any of these cases, they exit 0 despite failing.

Then the expr command gives 1 for success unless the output is the empty string or zero, in which case, 0 is success. 2 and 3 are failure.

Then there's cases where success or failure is ambiguous. When grep fails to find a pattern, it exits 1, but it exits 2 for a genuine failure (like permission denied). Klist also exits 1 when it fails to find a ticket, although this isn't really any more of a failure than when grep doesn't find a pattern, or when you ls an empty directory.

So, unfortunately, the unix powers that be don't seem to enforce any logical set of rules, even on very commonly used executables.

brian d foy
  • 121,466
  • 31
  • 192
  • 551
Frederick
  • 107
  • 1
  • 1
  • I was about to point out diff's behaviour too. wget also has detailed errors (e.g. 6 for authentication failure), but then they use 1 = generic error, 2..n = specific error – PypeBros Aug 30 '16 at 10:25
5

Programs return a 16 bit exit code. If the program was killed with a signal then the high order byte contains the signal used, otherwise the low order byte is the exit status returned by the programmer.

How that exit code is assigned to the status variable $? is then up to the shell. Bash keeps the lower 7 bits of the status and then uses 128 + (signal nr) for indicating a signal.

The only "standard" convention for programs is 0 for success, non-zero for error. Another convention used is to return errno on error.

Dean Povey
  • 8,585
  • 1
  • 37
  • 49
4

Standard Unix exit codes are defined by sysexits.h, as another poster mentioned. The same exit codes are used by portable libraries such as Poco - here is a list of them:

http://pocoproject.org/docs/Poco.Util.Application.html#16218

A signal 11 is a SIGSEGV (segment violation) signal, which is different from a return code. This signal is generated by the kernel in response to a bad page access, which causes the program to terminate. A list of signals can be found in the signal man page (run "man signal").

Daniel Schuler
  • 2,892
  • 1
  • 25
  • 26
1

When Linux returns 0, it means success. Anything else means failure, each program has its own exit codes, so it would been quite long to list them all... !

About the 11 error code, it's indeed the segmentation fault number, mostly meaning that the program accessed a memory location that was not assigned.

Amadeus45
  • 1,180
  • 2
  • 16
  • 27
  • 1
    It's always 11 because the kernel kills it and assigns the "exit value." Likewise, other types of Faults will always get the same exit value. – Alex Gartrell Jul 09 '09 at 06:04