Using exit to End a Script
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]
| Form | Exit code of the shell |
|---|---|
exit 0 | 0 (success) |
exit n | n, reduced to the range 0-255 |
exit | The 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:
- Stops running the script. Commands after
exitnever run. - Runs the
EXITtrap, if one is set (lesson 123). - 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). usageexits with 2, the conventional code for wrong usage;dieexits with 1 for a failure.[ ... ] || usagereads naturally: "the check holds, or show usage and stop".- The final
exit 0states 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.