Understanding Exit Codes

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 116 of 205

Every command that finishes in Bash leaves behind a small number called its exit code, also known as its exit status or return code. The number tells the caller whether the command succeeded and, if it failed, often what kind of failure happened. Conditions in if, the && and || operators, loops such as while, and error handling options such as set -e all work by looking at this number. Understanding exit codes is therefore the foundation for every error handling technique in the lessons that follow.

true
echo $?
false
echo $?
0
1

true is a command that does nothing and succeeds; false does nothing and fails. The special parameter $? holds the exit code of the most recent command (lesson 43 introduced it, and lesson 117 covers it in detail).

Zero Means Success

The central rule is simple and is the opposite of what many programmers expect from other languages:

Exit codeMeaning
0Success
1 to 255Failure of some kind

There is only one way to succeed and 255 ways to fail. This lets a program report different failure reasons with different numbers while keeping a single, unambiguous success value.

In languages such as C or Python, 0 is "false" in a boolean test. In the shell it is the other way round: a command whose status is 0 counts as "true" in if and while. The shell is not testing a value; it is asking "did this command succeed?"

if grep -q beta words.txt; then
    echo "found beta"
fi

grep -q prints nothing; it only sets its exit code. if runs the then branch because grep returned 0.

Where the Number Comes From

An exit code is produced by the program itself when it ends. A C program returns it from main() or passes it to exit(); a Python program passes it to sys.exit(); a Bash script uses the exit builtin (lesson 118) or, if it has none, returns the status of the last command it ran. The operating system keeps the value and hands it to the parent process (here, the shell) when the parent waits for the child.

python3 -c 'import sys; sys.exit(4)'
echo $?
sh -c 'exit 3'
echo $?
4
3

The value travels between processes as a single byte, which is why the range is 0 to 255. A larger number is reduced to its remainder after division by 256:

bash -c 'exit 255'; echo $?
bash -c 'exit 256'; echo $?
bash -c 'exit 300'; echo $?
255
0
44

exit 256 reports success, which is almost never what the author intended. Keep exit codes between 0 and 255; in practice, small numbers are used.

Builtins and functions also produce exit codes, without any separate process. A function returns its status with return (lesson 90), and builtins such as cd or read set it directly.

Exit Codes of Common Commands

Most commands document their exit codes in their manual pages (lesson 23). Many follow the pattern "0 success, 1 a normal negative answer, 2 an error":

grep -q beta words.txt;   echo "match: $?"
grep -q gamma words.txt;  echo "no match: $?"
grep -q beta nofile.txt;  echo "missing file: $?"
match: 0
no match: 1
grep: nofile.txt: No such file or directory
missing file: 2

For grep, "no match" (1) is not an error in the usual sense. It is an answer: the text is not there. Status 2 is a real problem, such as a file that cannot be read. A script that only checks for "non-zero" cannot tell these two situations apart, which is why the specific number matters.

diff follows the same idea:

Command012
grepa line matchedno line matchedan error occurred
difffiles are the samefiles differtrouble (for example, a missing file)
test / [ ]condition truecondition falseinvalid expression
GNU lssuccessminor problem (for example, a subdirectory could not be read)serious trouble (for example, a command-line argument that does not exist)
[ 5 -gt 3 ]; echo $?
[ 5 -gt 9 ]; echo $?
[ 5 -gt x ]; echo $?
0
1
bash: [: x: integer expression expected
2

Other well-known values: timeout returns 124 when it had to stop the command (lesson 142), and xargs returns 123 when one of the commands it ran failed (lesson 112).

Exit Codes Set by the Shell

Some codes are not chosen by the program at all, because the program never started or did not end normally. Bash sets these itself.

127: Command Not Found

nosuchcmd
echo $?
./missing.sh
echo $?
bash: nosuchcmd: command not found
127
bash: ./missing.sh: No such file or directory
127

Status 127 means Bash could not find anything to run: the name is not a builtin, function or alias, and no file with that name exists in PATH or at the given path.

126: Found but Cannot Run

printf 'echo hi\n' > noexec.sh
chmod 644 noexec.sh
./noexec.sh
echo $?
mkdir -p adir
./adir
echo $?
bash: ./noexec.sh: Permission denied
126
bash: ./adir: Is a directory
126

Status 126 means the file exists, but it could not be executed, usually because the execute permission is missing (lesson 27) or the path is a directory.

2: Misuse of a Builtin and Syntax Errors

Bash builtins return 2 when they are called with an invalid option, and a script that fails to parse ends with 2:

read -Z x
echo $?
bash -c 'syntax error ('
echo $?
bash: read: -Z: invalid option
read: usage: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
2
bash: -c: line 1: syntax error near unexpected token `('
bash: -c: line 1: `syntax error ('
2

Not every builtin error gives 2. cd a b c prints cd: too many arguments and returns 1. The manual page or help text of each builtin is the authority.

128 + N: Killed by a Signal

When a process is stopped by a signal (lessons 139 to 141), it does not exit with a code of its own. Bash reports 128 plus the signal number:

sleep 10 & pid=$!
kill -TERM "$pid"
wait "$pid"
echo $?
143

SIGTERM is signal 15, so the status is 128 + 15 = 143. kill -l converts a status above 128 back into a signal name:

kill -l 143
kill -l 130
kill -l 141
TERM
INT
PIPE
StatusSignalTypical cause
129SIGHUP (1)The terminal was closed
130SIGINT (2)The user pressed Ctrl + C
137SIGKILL (9)kill -9, or the system's out-of-memory killer
141SIGPIPE (13)The command wrote to a pipe whose reader had already exited
143SIGTERM (15)A normal kill, or a service manager stopping the process

Status 141 appears in ordinary pipelines and is usually harmless:

yes | head -n 1 > /dev/null
echo "${PIPESTATUS[*]}"
141 0

head exits after one line, and the next write by yes kills it with SIGPIPE. PIPESTATUS (lesson 61) shows each command's status. Lesson 120 explains why this matters for set -o pipefail.

Conventional Exit Code Values

CodeConventional meaning
0Success
1General failure, or a "no" answer (grep found nothing, false)
2Incorrect usage, invalid option, or a serious error
64-78Specific errors defined in sysexits.h (used by some programs)
124timeout stopped the command
126Command found but not executable
127Command not found
128 + NTerminated by signal N
255The highest value; ssh, for example, uses it for its own connection errors

The values 64 to 78 come from the C header file /usr/include/sysexits.h, originally from BSD mail software. They give names to common failure types:

grep -E 'EX_(USAGE|NOINPUT|SOFTWARE|CONFIG)' /usr/include/sysexits.h
#define EX_USAGE	64	/* command line usage error */
#define EX_NOINPUT	66	/* cannot open input */
#define EX_SOFTWARE	70	/* internal software error */
#define EX_CONFIG	78	/* configuration error */

Few shell scripts use these numbers, and nothing enforces them. They are useful when a script wants a documented, recognizable set of codes.

Exit Codes of Shell Constructs

Compound commands and lists have exit codes too, and the rules are consistent:

ConstructExit code
A pipeline a | bThe status of the last command, unless pipefail is set (lesson 120)
! command0 if the command failed, 1 if it succeeded
{ list; } and ( list )The status of the last command in the list
if with no branch taken0
A loop whose body never ran0
A plain assignment x=50
An assignment with command substitution x=$(cmd)The status of cmd
A functionThe value given to return, or the status of its last command
A scriptThe value given to exit, or the status of its last command
false | true;  echo "false | true -> $?"
true | false;  echo "true | false -> $?"
! false;       echo "! false -> $?"
( exit 7 );    echo "( exit 7 ) -> $?"
x=$(exit 5);   echo "x=\$(exit 5) -> $?"
if false; then :; fi; echo "if with no branch -> $?"
false | true -> 0
true | false -> 1
! false -> 0
( exit 7 ) -> 7
x=$(exit 5) -> 5
if with no branch -> 0

The last rule in the table explains a frequent surprise. A script with no exit statement reports the status of whatever ran last:

printf 'echo working\nfalse\n' > last.sh
bash last.sh; echo "status $?"
printf 'false\necho done\n' > last2.sh
bash last2.sh; echo "status $?"
working
status 1
done
status 0

The second script failed in its first line but reports success, because echo done succeeded. Exit codes are not accumulated; only the last one counts. Lessons 117 to 122 show how to notice a failure in the middle of a script.

Designing Exit Codes for Your Own Scripts

Other programs, schedulers such as cron (lesson 170), CI pipelines (lesson 177) and the person at the terminal all judge a script by its exit code. A script that prints "error" but exits with 0 is reported as successful everywhere.

This small checker uses three distinct codes, documented at the top so that callers can rely on them:

#!/usr/bin/env bash
# report.sh - check a log file for ERROR lines
# Exit codes: 0 no errors, 1 errors found, 2 file cannot be read

if [ ! -r "$1" ]; then
    echo "report: cannot read $1" >&2
    exit 2
fi

if ! grep -q ERROR "$1"; then
    echo "no errors"
    exit 0
fi

echo "errors found:"
grep -c ERROR "$1"
exit 1
printf 'INFO ok\nERROR disk\nERROR net\n' > app.log
printf 'INFO ok\n' > clean.log

./report.sh clean.log; echo "status $?"
./report.sh app.log;   echo "status $?"
./report.sh none.log;  echo "status $?"
no errors
status 0
errors found:
2
status 1
report: cannot read none.log
status 2

Like grep, it separates "the answer is no" (1) from "something went wrong" (2). A caller can act on each case:

./report.sh app.log > /dev/null
case $? in
    0) echo "clean" ;;
    1) echo "has errors" ;;
    *) echo "could not check" ;;
esac
has errors

The * branch catches every other code, including ones the script may add later and 126 or 127 if the script itself could not be started.

Guidelines that follow from the conventions above:

  • Exit with 0 only when the script did what it was asked to do.
  • Use 1 for a general failure and 2 for wrong usage, matching most command-line tools.
  • If more codes are needed, pick small numbers below 126 and document them.
  • Avoid 126, 127 and values above 128, which callers will read as "could not run" or "killed by a signal".
  • Send error messages to standard error (lesson 59) so that the exit code and the message both reach the caller without mixing with normal output.

The examples were run with Bash 5.2.21, GNU grep 3.11, GNU diffutils, GNU coreutils 9.4, Dash and Python 3. Error messages are shown in their interactive form; inside a script, Bash adds the script name and line number in front.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Understanding Exit Codes and get answers drawn from it.

Signed-in readers only.