SRE & Platform Engineering

Exit Codes Explained: What Do 0, 1, 127 and 137 Mean?

November 22, 2026
7
min read
SRE & Platform Engineering

An exit code is the integer a process hands back to its parent when it terminates. Zero means success, any non-zero value means failure, and the meaning of a specific non-zero value comes from convention, the shell, or the program that produced it. If you are searching what does exit code mean because a job died with 137, start from that rule and then decode the number.

Decoding follows the same order on every platform. Read the status immediately after the command finishes: $? in bash, $LASTEXITCODE in PowerShell, %ERRORLEVEL% in cmd. A 126 or 127 means the shell could not run the command. Above 128 on Unix, subtract 128 to get the signal number. A large negative number on Windows needs converting to hex for an NTSTATUS lookup. Anything else is defined by the tool, so check its documentation. The rest of this article covers what an exit code is, a reference table of common codes, signal termination above 128, how to check a code on Linux, macOS and Windows, how to set custom codes, using codes in CI and Kubernetes, common pitfalls, related concepts, and an FAQ.

What Is an Exit Code?

An exit code is the value the kernel delivers to the parent process when a child terminates. In bash, the exit status of a command is the value returned by the waitpid system call or an equivalent function. A C parent reads it the same way: WIFEXITED tells it the child terminated normally, and WEXITSTATUS returns the least significant 8 bits of the status.

The zero-means-success rule comes from Unix and is written into POSIX: zero, or EXIT_SUCCESS, conventionally indicates successful termination, and POSIX requires EXIT_SUCCESS to be zero. The design gives one well-defined way to signal success and many ways to signal different failures. Utilities such as make and the shells follow the same convention.

Everything that automates commands depends on this one integer. if, &&, || and set -e branch on it. GitHub Actions marks a step failed or succeeded from it. The kubelet decides whether to restart a container from it. A process that exits 0 after failing silently breaks all of those decisions at once.

The two values you will see most often are 0 and 1, and both have specific behavior worth knowing.

What Exit Code 0 Means

Exit code 0 means the process reports success. Several runtimes return it by default when you do not set anything:

PyCharm and IntelliJ print Process finished with exit code 0 when the program you ran exited with status 0. A JetBrains community reply describes this as the standard message, where 0 usually means the process terminated normally with no error condition. Zero is a claim the program makes about itself. A script that swallows an exception and exits normally still reports 0.

What Exit Code 1 Means

Exit code 1 is the conventional catch-all for “something went wrong.” No formal standard assigns it that meaning; Bash itself defines only zero versus non-zero plus the specific values covered below. The convention comes from practice: programs normally return 0 for success and 1 for failure, and Unix programs generally use 2 for command-line syntax errors and 1 for all other errors.

Python reports status 1 in two cases. When the interpreter ends on an unhandled exception other than SystemExit, the embedding API’s initialization call returns 1 (interpreter initialization); that is the embedding API’s return value, not the command-line interpreter’s exit status directly. Separately, sys.exit("some error message") prints the message to stderr and exits 1. In Java, System.exit(1) passes 1 to the launcher, and by convention any non-zero status indicates abnormal termination.

When PyCharm or IntelliJ shows Process finished with exit code 1, your program reported failure. The IDE does not know why. Look for a traceback or an error message on stderr in the console output above that line.

Valid Exit Code Range: 0 to 255 and Wraparound

A parent that uses wait() or waitpid() sees only the low 8 bits of the exit value. Only status & 0377 is available through those calls, which limits the visible range to 0 through 255 (POSIX exit). The full value reaches only a parent that uses waitid() or reads si_status in a SIGCHLD handler.

The masking produces wraparound. 256 is octal 0400, so 256 & 0377 is 0 and exit(256) looks like success to the parent. A negative value is all ones in its low byte under two’s complement, so exit(-1) arrives as 255. Larger values reduce modulo 256; 3809 becomes 225. You can see the effect from bash:

bash -c 'exit 256'; echo $?   # expected 0
bash -c 'exit 257'; echo $?   # expected 1
bash -c 'exit -1'; echo $?    # expected 255

POSIX leaves the shell exit utility’s status undefined outside 0 to 255, so the output above describes common shell behavior, not a guarantee. Python is stricter: its documentation says most systems require 0 to 127 and other values give undefined results. PowerShell on Unix translates -1 through -255 by adding 256 and turns any other out-of-range or non-numeric argument into 0. On Windows, PowerShell accepts the full [int] range because Windows exit codes are 32-bit.

Common Exit Codes Reference Table

These are the codes you will meet most often in shells, containers and CI logs:

CodeMeaningTypical causeFix
0SuccessCommand completed normallyNone
1General error (convention)Program-defined failure, unhandled Python exception, sys.exit("message")Read stderr and the program’s logs
2Incorrect usage, or “trouble” for grep, diff and makeInvalid option or missing argument to a bash builtin; error inside grep or diffCheck arguments against the tool’s usage text
126Command found but not executableMissing execute bit, or the path is a directorychmod +x the file or fix the path
127Command not foundTypo, binary not installed, not on PATHCheck spelling, PATH and installation
130Terminated by SIGINT (128 + 2)Ctrl+CExpected after an interrupt; otherwise find who sent SIGINT
137Terminated by SIGKILL (128 + 9)OOM kill, docker stop timeout, kill -9, liveness probe killCheck OOMKilled, memory limits and pod events
143Terminated by SIGTERM (128 + 15)docker stop, pod deletion, rolling updateUsually expected; handle SIGTERM and exit within the grace period
255Out-of-range or non-numeric exit argumentexit -1, exit with a non-numeric argumentReturn a value between 0 and 255

The bash-defined rows are 2, 126, 127 and the signal range. Bash builtins return 2 for incorrect usage, the shell returns 127 when a command is not found and 126 when it is found but not executable. For 255, the Advanced Bash-Scripting Guide lists “Exit status out of range”, and a bash-3.2 transcript shows exit a printing “numeric argument required” before $? reads 255.

Treat the signal rows as strong hints, not proof. A CNCF blog post warns that applications sometimes set these codes themselves, so a 143 does not always mean SIGTERM arrived.

Exit Codes Above 128: Signal Termination

A status above 128 usually means the process did not exit at all; a signal killed it. When a command terminates on fatal signal N, bash reports 128+N. The kernel reports signal death separately from a normal exit (WIFSIGNALED with WTERMSIG for the signal number), and the shell folds that into the single $? value.

POSIX is looser than bash. It requires only that a signal-terminated command get a status greater than 128 that identifies the signal in an implementation-defined way, and it allows shells to use values above 255. The 128+N rule is historical practice that bash follows.

The signals you are likely to see map to these statuses. The numbers below are identical on Linux x86/ARM, macOS and FreeBSD:

SignalNumberExit statusExample context
SIGHUP1129 
SIGINT2130Ctrl+C
SIGQUIT3131 
SIGABRT6134abort(), failed native assertion, JVM fatal error handling
SIGKILL9137OOM killer, kill -9, grace period expired
SIGSEGV11139 
SIGTERM15143docker stop, pod deletion

Other signal numbers differ by platform. SIGBUS is 7 on Linux x86/ARM and 10 on macOS, so a bus error shows up as 135 on one and 138 on the other. POSIX does not standardize signal numbers, which is why it gives no portable way to recover the signal from the status.

You do not need to memorize the table. kill -l accepts either a signal number or the $? value of a signal-terminated process and writes the signal name:

kill -l 137

That prints KILL in bash. Two exceptions catch people out:

  • Python’s subprocess reports a signal-killed child as a negative return code, -N, instead of 128+N.
  • GNU timeout returns 137 when it sends KILL, so a timeout that escalates to SIGKILL looks identical to an OOM kill in $?.

Exit Code 137 in Docker and Kubernetes

Exit code 137 in a container means something sent SIGKILL. A kernel OOM kill is one possible cause: Kubernetes memory limits are enforced by the kernel through OOM kills, and enforcement is reactive. The kernel acts when it detects memory pressure, not the instant usage crosses the limit. On cgroup v2 nodes, the kubelet sets memory.oom.group on each container cgroup by default, so an OOM event kills every process in that container together instead of picking off one child process.

The 137 alone does not tell you who sent the signal. kubectl describe pod shows the previous run’s termination under Last State, and an OOM kill looks like this:

Last State:   Terminated
  Reason:     OOMKilled
  Exit Code:  137

Start with the describe output, which shows the reason, exit code, restart count and the pod’s recent events:

kubectl describe pod <pod-name>

To read the raw lastState.terminated block (reason, exit code, finishedAt and any termination message the container wrote), query the pod status directly:

kubectl get pod <pod-name> -o jsonpath='{.status.containerStatuses[*].lastState.terminated}'

Events record kills that Kubernetes initiated, such as failed liveness probes, and this command lists them for the namespace:

kubectl get events

A node that ran out of memory overall records a Warning OOMKilling event on the node, which this command shows:

kubectl describe nodes

Match what you find to one of these patterns. Each has a different cause and a different check:

  • OOMKilled with 137: The container exceeded its memory limit and the kernel killed it. Compare actual usage against resources.limits.memory and either raise the limit or reduce the workload’s memory use.
  • Error with 137 and liveness events: The kubelet killed the container after failureThreshold failed probes (default 3). Look for Unhealthy events with “Liveness probe failed” and “failed liveness probe, will be restarted”. In one reported case, a container killed after an HTTP 500 probe failure showed Reason: Error with exit code 137, so the reason field alone does not separate a liveness kill from other SIGKILLs.
  • Error with 137 after a deletion: The pod was deleted, the container ignored SIGTERM, and the runtime sent SIGKILL when terminationGracePeriodSeconds expired (default 30 seconds). Make the process handle SIGTERM and exit inside the grace period.
  • Error with 143: The container received SIGTERM and exited on it, for example during a deployment update or deletion. Kubernetes still labels the reason “Error”.
  • Node-level OOM: The kernel picked a victim by oom_score across the whole node. The pod using the most memory is not guaranteed to be the one that dies.

On the node itself, the kernel log shows lines such as oom-kill:constraint=CONSTRAINT_MEMCG and “Memory cgroup out of memory: Killed process” for a cgroup OOM. Running this requires host access:

sudo dmesg -wH

Plain Docker exposes the distinction as container state in docker inspect. A container killed under memory load can show State.OOMKilled as true alongside ExitCode 137:

docker inspect --format '{{.State.Status}} OOMKilled={{.State.OOMKilled}} ExitCode={{.State.ExitCode}}' <container>

If OOMKilled is false and the exit code is 137, suspect docker stop. It sends SIGTERM, waits 10 seconds for Linux containers and 30 for Windows containers, then sends SIGKILL.

A process running as PID 1 under a shell-form CMD often never sees the SIGTERM, because the shell does not forward it; Docker recommends the exec form of CMD and ENTRYPOINT, or a signal proxy such as tini or dumb-init.

Docker also reserves three codes of its own for docker run. 125 means the Docker daemon itself failed (for example an unknown flag), 126 means the contained command could not be invoked, and 127 means it could not be found. Any other code is the container command’s own exit status.

How to Check an Exit Code on Linux, macOS and Windows

Each shell stores the last exit status in a different place, and each place behaves differently:

ShellWhere the status livesWhat it holds
bash, zsh, sh$?Exit status of the most recent command
bashPIPESTATUS arrayStatus of every command in the last pipeline
PowerShell$LASTEXITCODEExit code of the last native program or script
PowerShell$?True or False for the last command’s success
cmd.exe%ERRORLEVEL%Exit code of the last program cmd ran

On Linux and macOS, read $? on the line immediately after the command. Any command in between, including echo, replaces it:

echo $?

In PowerShell, $LASTEXITCODE holds the number from the last native executable or script:

$LASTEXITCODE

PowerShell’s $? reports success as a Boolean:

$?

The two variables diverge for cmdlets: for a native executable, $? is True exactly when $LASTEXITCODE is 0, but for a cmdlet or function, $? turns False when it writes an error while $LASTEXITCODE does not change, because cmdlets do not set exit codes. Since PowerShell 7, wrapping a command in (...), $(...) or @(...) no longer resets $? to True. If you want a non-zero native exit code to raise an error you can catch with try/catch, set $PSNativeCommandUseErrorActionPreference = $true, which has been stable since PowerShell 7.4.

In cmd.exe, expand the dynamic variable:

echo %ERRORLEVEL%

Two cmd behaviors trip up batch authors. if errorlevel 1 is true when the last exit code was equal to or greater than 1, not equal to it. And if anything creates a real environment variable named ERRORLEVEL, %ERRORLEVEL% expands to that variable instead of the actual exit code.

Windows Exit Codes: 9009 and HRESULT Values

Windows uses 32-bit exit codes, which produces two kinds of values Unix users never see:

  • The first is 9009, which cmd.exe sets when you run a command it does not recognize. The ss64 cmd reference states that running a non-existent command sets %ERRORLEVEL% to 9009, and build logs show error MSB6006: "cmd.exe" exited with code 9009 next to “is not recognized as an internal or external command”. When a build step exits 9009, check that the executable is on PATH and that the command line has no stray line breaks or broken quoting.
  • The second kind is a large negative number such as -1073741819. When a Windows process crashes on an unhandled exception, the exception code becomes the exit code. NTSTATUS error values sit in the range 0xC0000000 to 0xFFFFFFFF, so their top bit is set, and any tool that reads the exit code as a signed 32-bit integer prints a negative number.

These are the values you will meet most often, with the signed decimal form you will see in logs:

Signed decimalHexNameMeaning
-10737418190xC0000005STATUS_ACCESS_VIOLATIONInvalid memory access
-10737407910xC0000409STATUS_STACK_BUFFER_OVERRUNFail-fast termination
-10737415100xC000013ASTATUS_CONTROL_C_EXITTerminated by Ctrl+C
-10737415710xC00000FDSTATUS_STACK_OVERFLOWStack overflow
-5324627660xE0434352.NET CLR exceptionUnhandled managed exception

The four STATUS_ rows use the names and messages in Microsoft’s NTSTATUS table; 0xE0434352 is the exception code .NET applications raise for CLR exceptions. 0xC0000409 is misleadingly named: Raymond Chen explains that STATUS_STACK_BUFFER_OVERRUN does not mean a stack buffer overran; it means the application terminated itself immediately through a fail-fast path.

To look up a code, convert the signed value to unsigned hex. Add 2^32 (4294967296) to the negative number, then convert to hex: -1073741819 + 4294967296 = 3221225477, which is 0xC0000005. In bash, masking to 32 bits does both steps:

printf '0x%X\n' $(( -1073741819 & 0xFFFFFFFF ))

In .NET, the "X" format specifier formats an Int32 as hex and prints negative values as their eight-digit two’s-complement form. With the hex value, the Microsoft Error Lookup Tool returns the name and shows both hex and decimal.

You can identify the class of crash from the exit code, but you need more evidence to find the root cause. Check the Windows Application event log at the failure timestamp to find the faulting module.

How to Set Custom Exit Codes in Scripts and Programs

Pick codes that callers can interpret without guessing, keep them between 0 and 255, and document them. Avoid 126, 127 and anything above 128 for your own failures, because shells and container runtimes already use those values to report that your program could not start or was killed. If you want a structured scheme, the BSD sysexits.h codes (64 to 78) are one option. Python’s guidance is the most portable constraint: most systems require values from 0 to 127.

Bash and Shell Scripts: exit n

exit n ends the script and returns n to the parent. Without an argument, exit returns the status of the last command executed, and a script that reaches its last line does the same. Inside a function, use return n instead; bash keeps the least significant 8 bits of n.

Any trap on EXIT runs before the shell terminates, which lets you clean up while preserving the original status:

#!/usr/bin/env bash
cleanup() {
  status=$?
  rm -f "$tmpfile"
  exit "$status"
}
trap cleanup EXIT

tmpfile=$(mktemp)
curl -fsS https://example.com/health > "$tmpfile" || exit 3
grep -q ready "$tmpfile" || { echo "service not ready" >&2; exit 4; }

Capturing $? as the first line of the trap matters. Running rm first would replace the status with rm’s own result, and the script would report success after a failure.

Python sys.exit, C exit() and Java System.exit

Python’s sys.exit accepts an integer, None or any other object. An integer becomes the exit status, None means 0, and any other object is printed to stderr with status 1:

import sys

if not config_ok:
    sys.exit("config file missing")   # prints to stderr, exits 1
sys.exit(0)

sys.exit works by raising SystemExit, so finally blocks run and an outer except can intercept it. It exits the process only when called from the main thread. Since Python 3.6, an error during interpreter cleanup after SystemExit (such as a failure flushing buffered stdout) changes the exit status to 120.

In C, return from main or call exit(). EXIT_SUCCESS and EXIT_FAILURE from <stdlib.h> are the portable values; C89 added EXIT_FAILURE because there had been no portable way to signal failure. A parent uses waitpid and the status macros to tell a normal exit from a signal death. This example shows the 8-bit masking from earlier:

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

int main(void) {
    pid_t pid = fork();
    if (pid == -1) { perror("fork"); return 1; }
    if (pid == 0) {
        exit(256);          /* parent observes 0 */
    }
    int status;
    if (waitpid(pid, &status, 0) == -1) { perror("waitpid"); return 1; }
    if (WIFEXITED(status))
        printf("exited, status=%d\n", WEXITSTATUS(status));
    else if (WIFSIGNALED(status))
        printf("killed by signal %d\n", WTERMSIG(status));
    return 0;
}

Only use WEXITSTATUS after WIFEXITED returns true. For a status stored by wait(), exactly one of WIFEXITED and WIFSIGNALED is non-zero.

In Java, System.exit(n) is equivalent to Runtime.getRuntime().exit(n) and never returns normally:

public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("usage: tool <file>");
        System.exit(2);
    }
    System.exit(0);
}

A JVM crash is a different event from System.exit. HotSpot writes a fatal error log named hs_err_pid<pid>.log to the current directory for a standalone application, and it calls abort() after fatal error handling, which raises SIGABRT. Under the 128+N rule, SIGABRT on Linux gives a status of 134 (128 + 6). With -XX:+ExitOnOutOfMemoryError, the JVM exits with code 3 on the first out-of-memory error.

.NET Environment.ExitCode and Main Return Values

In .NET, return the exit code from Main when you can. An int Main or async Task<int> Main returns its value to the operating system, and the runtime waits for the returned Task to complete before the process exits:

static async Task<int> Main(string[] args)
{
    return await AsyncConsoleWork();
}

Top-level statements follow the same rule: use return with a value, and the compiler generates an int or Task<int> entry point.

Environment.ExitCode applies when Main returns void; the property is ignored when Main does not return void. Its initial value is 0, and because it is a signed 32-bit integer, values at or above 0x80000000 produce a negative exit code.

Environment.Exit(n) is the blunt option. It terminates the process immediately even if other threads are running, and a finally block around the call does not execute. A return from Main waits for foreground threads and runs finally blocks. Use Environment.Exit when you must force a non-zero code from deep inside a hosted service; the .NET Windows service guidance uses Environment.Exit(1) so the service manager’s recovery options can restart the process.

On Windows, an unhandled managed exception can surface as -532462766 (0xE0434352). A reported Linux runtime case shows an unhandled exception ending through SIGABRT, with a typical status of 134.

Using Exit Codes in Automation and CI Pipelines

Every automation layer decides whether to continue or stop by reading exit status. A shell decides whether to run the next command, a CI runner decides whether a step passed, and the kubelet decides whether to restart a container. The shell rules come first, because CI runners and container entrypoints run shell scripts.

Chaining Commands With && and ||

&& runs the next command only if the previous one exited 0, and || runs it only if the previous one failed:

make build && make test && ./deploy.sh
command -v jq >/dev/null || { echo "jq is required" >&2; exit 1; }

The fallback pattern also works for capturing a failure without stopping the script. GitLab’s script documentation uses this form:

exit_code=0
false || exit_code=$?
if [ "$exit_code" -ne 0 ]; then echo "previous command failed with $exit_code"; fi

The status of an && or || list is the status of the last command that ran. Under set -e, a failure in any command except the one after the final && or || does not stop the script, so false && echo yes lets execution continue.

set -e and set -o pipefail

set -e makes bash exit when a command returns non-zero, with deliberate exceptions. The shell does not exit when the failing command is part of an if or while/until test, any command in an && or || list other than the last, any command in a pipeline but the last, or a command negated with !. A function called as a condition, such as f || echo failed, runs its whole body with -e ignored, even if you wrote set -e inside it.

Pipelines are where the default behavior surprises people. A pipeline’s status is the status of its last command, so an earlier failure disappears. pipefail changes this: the pipeline returns the status of the rightmost command that exited non-zero, or 0 if all succeeded. This terminal session shows the difference:

$ false | true; echo $?
0
$ set -o pipefail
$ false | true; echo $?
1
$ false | true | false; echo "${PIPESTATUS[@]}"
1 0 1

PIPESTATUS holds the status of every command in the most recent foreground pipeline, and ! does not change its values. Copy it immediately, because the next command replaces it:

grep foo app.log | head -n5
codes=("${PIPESTATUS[@]}")

pipefail is not safe to turn on blindly. Commands that exit early on purpose make upstream writers fail. In yes | head -n1, head exits after one line, yes dies from SIGPIPE with status 141 (128 + 13), and with pipefail the pipeline reports failure. GNU grep’s manual gives the same warning: under set -e -o pipefail, a command piped into grep can fail when grep exits before reading all its input.

CI Jobs and Kubernetes Restart Policies

CI runners translate exit codes into step results, and each runner invokes the shell differently. GitHub Actions runs a step with shell: bash as bash --noprofile --norc -eo pipefail {0}. A step with no shell on a non-Windows runner gets bash -e {0}, without pipefail, so a failure early in a pipeline does not fail the step unless you set shell: bash explicitly.

For pwsh, the runner prepends $ErrorActionPreference = 'stop' and appends a line that exits with $LASTEXITCODE.

To let a step fail without failing the job, set continue-on-error: true. The step’s outcome is then failure while its conclusion is success, so a later step can still branch on steps.<id>.outcome.

GitLab CI fails the job and stops running commands when a script command returns non-zero. allow_failure:exit_codes lets you name specific codes that count as an allowed failure while every other non-zero code still fails the job:

test_job:
  script:
    - exit 137
  allow_failure:
    exit_codes:
      - 137
      - 255

Kubernetes uses container exit codes to decide restarts:

  • With restartPolicy: Always (the default), the kubelet restarts the container after any exit, including 0.
  • OnFailure restarts only on a non-zero exit.
  • Never does not restart.

Repeated crashes put the container into CrashLoopBackOff: the kubelet waits 10s, 20s, 40s and so on between restarts, capped at 300 seconds, and resets the timer once the container runs for 10 minutes without problems. In Kubernetes 1.35 and later, the KubeletCrashLoopBackOffMax feature gate lets you lower the per-node maximum through crashLoopBackOff.maxContainerRestartPeriod in the kubelet configuration, between 1s and 300s.

Two features act on specific exit codes. Container restart rules (restartPolicyRules, available since 1.35) match the container’s exit code against a list of values and restart that container in place, even when the Pod’s restartPolicy is Never.

For Jobs, podFailurePolicy with onExitCodes can fail the whole Job on a specific code, for example by treating exit code 42 as a fatal error while other failures count toward backoffLimit (Job documentation example). A Job that uses podFailurePolicy must set the Pod template’s restartPolicy to Never.

Common Exit Code Pitfalls and Misconceptions

Most exit code bugs come from assuming a rule that only some tools follow, or from losing the status before anyone reads it.

Non-Zero Does Not Always Mean an Error

Misconception: any non-zero exit means the command failed. Correction: for several standard tools, exit code 1 reports a result such as no match, differences found, or an out-of-date target. GNU grep exits 0 when a line is selected, 1 when none are, and 2 on error, which means set -e can kill your script because a search found nothing. With -q, grep exits 0 if a line is selected even if an error also occurred.

These tools document codes you should handle explicitly:

ToolDocumented codes
grep0 match found, 1 no match, 2 error
diff0 no differences, 1 differences found, 2 trouble
make0 success, 2 error; with -q, 1 means a target is out of date
curl6 could not resolve host, 7 could not connect, 28 operation timeout; 22 for HTTP 400+ with -f
git128 fatal error (die), 129 command-line usage error; git diff --exit-code returns 1 when there are differences

curl deserves a specific warning. By default it does not treat HTTP error responses as failure, so a 500 from your health endpoint exits 0. Add -f (or --fail-with-body to keep the response body) to get exit code 22 for responses of 400 or greater.

When a non-zero code is an expected answer, test for it directly instead of letting set -e decide:

if grep -q "ERROR" app.log; then echo "errors found"; fi

Exit Codes Are Not Standardized Across Tools and Operating Systems

Misconception: exit code 3 or 64 means the same thing everywhere. Correction: zero for success is the only universal rule. POSIX adds only 126 for “found but not executable”, 127 for “not found”, and values above 128 for signal termination in the shell. Beyond that, each program defines its own codes; Docker, for example, reuses 125 to 127 for its own failures.

The closest thing to a shared scheme is sysexits.h, which Eric Allman created in 1980 for delivermail, later renamed sendmail. Its codes start at 64 to avoid clashing with values random programs return:

  • 64 EX_USAGE: command used incorrectly
  • 65 EX_DATAERR: incorrect input data
  • 66 EX_NOINPUT: input file missing or unreadable
  • 69 EX_UNAVAILABLE: service unavailable
  • 70 EX_SOFTWARE: internal software error
  • 75 EX_TEMPFAIL: temporary failure, retry later
  • 77 EX_NOPERM: insufficient permission
  • 78 EX_CONFIG: configuration error

Adoption is narrow. Postfix expects delivery commands to follow these codes, and Python exposes them as os.EX_* constants, but FreeBSD’s man page marks the interface deprecated and discourages its use, and the OpenBSD page calls the codes non-portable. Windows follows none of this; its crash codes are NTSTATUS values. Check each tool’s documentation before you branch on a specific number.

Lost Exit Status in Pipelines and Subshells

Misconception: if a command fails, $? or set -e will catch it. Correction: bash discards or masks exit status in several common constructs. The most frequent is reading $? too late; $? reflects only the most recent command, so a debugging echo in between replaces the status you wanted:

make build
echo "build finished"
echo $?   # status of the echo above, always 0

Other constructs lose status in less obvious ways:

  • Pipelines: Without pipefail, only the last command’s status survives. Every command in a multi-command pipeline runs in its own subshell.
  • local and declare: local v=$(cmd) returns the status of local, which is 0, so a failure in cmd does not trigger set -e. Declare first, then assign: local v; v=$(cmd).
  • Command substitution: Outside POSIX mode, bash clears -e inside $(...), so x=$(false; echo one) sets x to one. Enable shopt -s inherit_errexit (bash 4.4 and later) to keep -e active inside the substitution.
  • Process substitution: <(cmd) discards the exit code; the main script cannot see it.
  • Background jobs: A command started with & returns 0 immediately. Use wait $! to collect its real status.

POSIX gives a compact example of a subshell inside a pipeline. With set -e, (false; echo one) | cat; echo two stops the subshell before echo one, but echo two still runs because the pipeline’s status is cat’s 0.

Exit status identifies how a process terminated, stderr carries the diagnostic text, and Kubernetes adds termination reasons and events on top of both.

  • Signals explain codes above 128. SIGKILL cannot be caught, blocked or ignored. SIGTERM can be handled.
  • stderr carries the explanation that the exit code cannot. The exit code is a single integer delivered through waitpid; the error message travels separately on file descriptor 2. Python’s sys.exit("message") uses both channels: the text goes to stderr and the status is 1. Redirecting stderr to /dev/null throws away diagnostic text.
  • Kubernetes adds a third layer: the termination reason. lastState.terminated records a reason (OOMKilled, Error), an exitCode, start and finish times, and an optional message the container writes to its termination message path. Events record the kubelet’s own actions, such as liveness probe failures.

Diagnosing a 137 correctly means putting the exit code, the reason, the events and the container’s last log lines on one timeline.

groundcover’s eBPF sensor runs as a DaemonSet, one pod per node, and collects container logs, metrics and traces from the Linux kernel without SDKs or code changes, while groundcover stores Kubernetes events in ClickHouse alongside logs and traces, queryable through SQL and gcQL. That correlation can place an event such as an Unhealthy probe failure beside the logs the container wrote, and the groundcover MCP Server exposes the same logs, traces, metrics and events to compatible AI agents in your IDE or incident workflow. If you want to try this on your own cluster, the free plan includes BYOC (Bring Your Own Cloud, where your data plane runs in your own cloud account) and requires no credit card.

FAQs

Exit code 1 is the conventional general failure. Exit code 2 usually means incorrect usage: bash builtins return 2 for invalid options or missing arguments, and Python’s documentation notes Unix programs use 2 for command-line syntax errors. For grep, diff and make, 2 means an error occurred, while 1 means “no match”, “files differ” or “target out of date”.

Run echo $? immediately after the command in bash, zsh or sh. In PowerShell, read $LASTEXITCODE for native programs and scripts, or $? for a Boolean success flag. In cmd.exe, run echo %ERRORLEVEL%.

Windows exit codes are 32-bit, and a process that crashes on an unhandled exception exits with the exception’s NTSTATUS code. Error codes have the top bit set, so tools that print them as signed integers show negative values. Add 4294967296 and convert to hex to look them up; -1073741819 is 0xC0000005, an access violation.

On Unix, a parent using wait() or waitpid() sees only the low 8 bits, so exit(256) reads as 0 and exit(257) as 1. The full value is available only through waitid() or si_status in a SIGCHLD handler. On Windows, exit codes use the full 32-bit range.

Only 0 for success is universal. POSIX specifies 127 for a command not found and 126 for one found but not executable, and requires a signal-terminated command to get a status above 128; 128+N is a common convention, not a POSIX guarantee. Signal numbers also vary by platform (SIGBUS is 7 on Linux x86 and 10 on macOS), and every program defines its own non-zero codes. C’s exit() and Java’s System.exit pass your chosen status to the operating system, and on Unix a parent sees only its low 8 bits; Python’s documentation says most systems require values from 0 to 127.

127 means the shell could not find the command at all, usually a typo or a binary missing from PATH. 126 means the shell found the file but could not execute it, usually a missing execute bit or a path that points to a directory. POSIX chose the two values specifically so you can tell “not found” apart from “found but cannot run”.

Sign up for Updates

Keep up with all things cloud-native observability.

We care about data. Check out our privacy policy.