Using exit to End a Script

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 118 of 205

The exit builtin ends the shell that runs it and hands an exit code to whoever started it. In a script, that means the script stops at that line, no further commands run, and the caller receives the number you chose. exit is how a script reports success or failure on purpose instead of leaving the result to whatever command happened to run last (lesson 116).

#!/usr/bin/env bash
echo "before"
exit 3
echo "after"

Running this script prints only before, and its exit code is 3:

bash demo.sh
echo "status $?"
before
status 3

Syntax

exit [n]
FormExit code of the shell
exit 00 (success)
exit nn, reduced to the range 0-255
exitThe status of the last command that ran before exit

The argument must be an integer. As lesson 116 explained, the value is passed between processes as one byte, so exit 256 gives 0 and exit 300 gives 44. Bash also accepts a negative number: exit -1 gives 255. Dash, the /bin/sh on Debian and Ubuntu, rejects it:

bash -c 'exit -1'; echo "bash: $?"
dash -c 'exit -1'; echo "dash: $?"
bash: 255
dash: 1: exit: Illegal number: -1
dash: 2

Use values from 0 to 255, and prefer small, documented ones.

What Happens When exit Runs

When Bash runs exit, it:

  1. Stops running the script. Commands after exit never run.
  2. Runs the EXIT trap, if one is set (lesson 123).
  3. Ends the shell process with the chosen exit code, which the parent process (a terminal shell, cron, a CI system) receives.

Open files are closed and memory is released by the operating system. Temporary files are not removed automatically; that is what the EXIT trap is for (lesson 124).

bash -c 'trap "echo cleanup runs" EXIT; echo work; exit 2'
echo "status $?"
work
cleanup runs
status 2

If the trap itself calls exit with a value, that value replaces the original:

bash -c 'trap "echo cleanup; exit 9" EXIT; exit 2'
echo "status $?"
cleanup
status 9

exit Without an Argument

A bare exit passes on the status of the command that ran immediately before it:

bash -c 'false; exit'; echo "after false: $?"
bash -c 'true; exit';  echo "after true: $?"
after false: 1
after true: 0

This is convenient after a failing command:

cp nofile.txt backup.txt 2> /dev/null || exit

If cp fails, exit runs and the script ends with the status of cp (1 here).

A bare exit can also pass on the wrong status, because "the last command" is not always the one you think. Inside an if branch whose condition used !, the last status is the inverted one, which is 0:

bash -c 'if ! cp nofile x 2> /dev/null; then exit; fi'
echo "status $?"
status 0

The script ended at the failure but reported success. An empty variable has the same effect: exit $rc with rc empty is a bare exit, and if the line before was an assignment, the status is 0. Write an explicit number whenever the script is ending because of an error:

if ! cp nofile x 2> /dev/null; then
    echo "cp failed" >&2
    exit 1
fi

Invalid Arguments

A non-numeric argument is an error. Bash prints a message and the shell ends with status 2:

bash -c 'exit abc; echo continued'
echo "status $?"
bash -c 'exit 3.5'
echo "status $?"
bash: exit: abc: numeric argument required
status 2
bash: exit: 3.5: numeric argument required
status 2

With two arguments, Bash 5.2.21 printed exit: too many arguments and the script ended with status 1. Always pass at most one integer, and quote a variable used as the argument (exit "$rc") so that an empty value becomes an error you notice rather than a silent bare exit.

Where exit Ends Something Else

exit ends the shell process that runs it. In most places that is the script, but several constructs run commands in a separate process, a subshell, and there exit ends only that subshell.

Subshells and Command Substitution

( exit 4 )
echo "still running, subshell gave $?"
v=$(exit 6)
echo "command substitution gave $?"
still running, subshell gave 4
command substitution gave 6

The subshell's exit code becomes the status of the ( ) or $( ) construct, and the script carries on.

Pipelines

Each part of a pipeline runs in its own subshell (lesson 61), so exit inside a while read loop that receives input from a pipe leaves only the loop:

printf 'a\nstop\nb\n' | while read -r line; do
    [ "$line" = stop ] && exit 3
    echo "$line"
done
echo "after the loop, status $?"
a
after the loop, status 3

The script continues after the loop. To end the whole script from such a loop, feed the loop with a redirection or process substitution instead of a pipe (lesson 114), so that it runs in the main shell, or check the loop's status afterwards:

printf 'a\nstop\nb\n' | while read -r line; do
    [ "$line" = stop ] && exit 3
done || exit

Functions

A function runs in the current shell, so exit inside a function ends the whole script, not just the function. Use return to leave only the function (lesson 90):

die() {
    echo "error: $1" >&2
    exit 1
}
echo "start"
die "boom"
echo "never printed"
start
error: boom

The script's exit code is 1. This behavior is exactly what a die helper needs, and it is why library functions meant for reuse (lesson 96) usually return a status and let the caller decide whether to exit.

Sourced Files

A file loaded with source (lesson 95) runs in the calling shell. exit in that file ends the caller:

printf 'echo "in lib"\nexit 7\n' > lib.sh
bash -c 'source ./lib.sh; echo "after source"'
echo "status $?"
in lib
status 7

after source never appears. If you source such a file into an interactive terminal, the terminal window closes. Sourced files should use return to stop early:

printf 'echo "in lib2"\nreturn 7\n' > lib2.sh
bash -c 'source ./lib2.sh; echo "after source, status $?"'
in lib2
after source, status 7

return Outside a Function

The reverse mistake is using return at the top level of a script. Bash prints an error and continues:

bash -c 'return 3; echo continued'
bash: return: can only `return' from a function or sourced script
continued

Use exit at the top level and return inside functions and sourced files.

Interactive Shells

Typing exit in a terminal closes that shell, and the terminal window or SSH session usually closes with it. The code given to exit becomes the shell's exit status, which matters when the shell itself was started by another program.

Exiting on Success Early

exit 0 is useful when there is nothing left to do, for example when a loop finds what it was looking for:

for i in 1 2 3; do
    echo "$i"
    [ "$i" -eq 2 ] && exit 0
done
echo "end"
1
2

A script that reaches its last line ends anyway, so a final exit 0 is not required. Many authors still write it, because it documents that reaching the end means success and protects against a later edit that adds a failing command at the bottom. The two scripts in lesson 116 that ended in false and echo show why the last line matters without it.

A Script with usage and die Helpers

Most scripts end in one of three ways: success, wrong usage, or a runtime failure. Two small functions make each path one line long:

#!/usr/bin/env bash
usage() {
    echo "usage: ${0##*/} SOURCE DEST" >&2
    exit 2
}

die() {
    echo "${0##*/}: $*" >&2
    exit 1
}

[ $# -eq 2 ] || usage
[ -r "$1" ]  || die "cannot read $1"
cp -- "$1" "$2" || die "copy to $2 failed"

echo "copied $1 to $2"
exit 0
./usage.sh;                          echo "status $?"
./usage.sh nofile out.txt;           echo "status $?"
./usage.sh words.txt nodir/out.txt;  echo "status $?"
./usage.sh words.txt copy.txt;       echo "status $?"
usage: usage.sh SOURCE DEST
status 2
usage.sh: cannot read nofile
status 1
cp: cannot create regular file 'nodir/out.txt': No such file or directory
usage.sh: copy to nodir/out.txt failed
status 1
copied words.txt to copy.txt
status 0

How it works:

  • ${0##*/} is the script name without its directory (lesson 54), so messages read like those of other command-line tools.
  • Messages go to standard error with >&2, so they do not mix with the normal output a caller may capture (lesson 59).
  • usage exits with 2, the conventional code for wrong usage; die exits with 1 for a failure.
  • [ ... ] || usage reads naturally: "the check holds, or show usage and stop".
  • The final exit 0 states that reaching the end is success.

The script prints a useful message for every failure and ends with a code that a caller can test. Lesson 125 is about writing such messages, and lessons 127 to 133 extend argument checking.

exit and Error Messages

The exit code and the message are separate. A script can print error and still exit with 0:

bash -c 'echo "error" >&2; exit 0' 2> /dev/null
echo "status $?"
status 0

Anyone checking the status, such as cron, a CI job or if ./script.sh, will treat this run as a success. Pair every error message with a non-zero exit (or return in a function), and keep exit 0 for the paths where the script really did its job.

The examples were run with Bash 5.2.21, Dash and GNU coreutils 9.4. Error messages are shown in their interactive form; in 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 Using exit to End a Script and get answers drawn from it.

Signed-in readers only.