Returning Status Codes from Functions
Every command in Bash finishes with an exit status, a number from 0 to 255 that tells the shell whether the command succeeded (lesson 116). Functions follow the same rule. A function ends with a status, and the caller reads it with $? or uses it directly in an if, while, && or ||.
The return command sets that status on purpose. A function cannot return text or numbers as a value in the way functions of other languages do; it can only return a status. Lesson 91 explains how to send data back with echo.
Syntax
return [N]
N is the status, a number from 0 to 255. By convention, 0 means success and any other number means a kind of failure.
Basic Example
check() {
return 3
}
check
echo "status: $?"
Output:
status: 3
The call check ran the function, and return 3 ended it immediately with status 3. The variable $? (lesson 43) holds the status of the most recent command, which was the function call. The status of the call is the status of the function.
The Status When There Is No return
A function that does not use return ends with the status of the last command that ran inside it:
f_ok() { echo "ran"; }
f_bad() { echo "ran"; false; }
f_ok >/dev/null; echo "f_ok: $?"
f_bad >/dev/null; echo "f_bad: $?"
f_ok: 0
f_bad: 1
In f_ok the last command is echo, which succeeded, so the status is 0. In f_bad the last command is false, which always fails with status 1. This is the reason why many functions need no return at all: a function whose last command is the test or action that matters already reports the right status.
A return without a number also uses the status of the last command:
g() { false; return; }
h() { true; return; }
g; echo "bare return after false: $?"
h; echo "bare return after true: $?"
bare return after false: 1
bare return after true: 0
Using a Function in Conditions
Because the status decides the result of a condition, a function can be used as a test. Lesson 66 explained that if runs a command and looks at its status; a function is just another command:
is_even() { (( $1 % 2 == 0 )); }
for n in 4 7; do
if is_even "$n"; then
echo "$n is even"
else
echo "$n is odd"
fi
done
4 is even
7 is odd
The body of is_even is one arithmetic command (( ... )) (lesson 73). It succeeds (status 0) when the remainder is 0 and fails (status 1) when it is not. No return is needed. The same function works in lists with the logical operators (lesson 74):
is_even 10 && echo "10: and-branch"
is_even 3 || echo "3: or-branch"
if ! is_even 9; then echo "9 is not even"; fi
10: and-branch
3: or-branch
9 is not even
A function can control a loop as well:
more() { (( n < 3 )); }
n=0
while more; do
n=$((n + 1))
echo "n=$n"
done
n=1
n=2
n=3
A function used this way is often called a predicate: a function that answers a yes-or-no question through its status. Name predicates like questions (is_even, file_exists, has_prefix), so that the conditions read like sentences.
Reading $? at the Right Moment
$? holds the status of the last command only, and every command changes it, including echo:
bad() { return 4; }
bad
echo "first echo sees: $?"
echo "second echo sees: $?"
first echo sees: 4
second echo sees: 0
The first echo shows the status of bad. But echo itself succeeded, so the second echo shows 0. If you need the status later, copy it to a variable right away:
bad
saved=$?
echo "saved: $saved"
echo "saved again: $saved"
saved: 4
saved again: 4
Choosing Status Values
The range of a status is 0 to 255, and the rest follows convention:
| Status | Usual meaning |
|---|---|
| 0 | Success |
| 1 | A general failure |
| 2 | Wrong usage, for example missing or invalid arguments |
| 126, 127 | Command found but not executable, command not found |
| 128 + N | The command was ended by signal N (130 for Ctrl + C, 143 for TERM) |
A function can use 1 for "no" or "failed" and keep other numbers (for example 10, 11 and 12) for specific problems. Giving the numbers names makes the code readable:
readonly E_OK=0 E_MISSING=10 E_EMPTY=11 E_UNREADABLE=12
check_file() {
local f=$1
[ -e "$f" ] || return "$E_MISSING"
[ -s "$f" ] || return "$E_EMPTY"
[ -r "$f" ] || return "$E_UNREADABLE"
return "$E_OK"
}
for f in full.txt empty.txt nope.txt; do
check_file "$f"
case $? in
0) echo "$f: ok" ;;
10) echo "$f: missing" ;;
11) echo "$f: empty" ;;
12) echo "$f: unreadable" ;;
esac
done
In a folder with a one-line full.txt, an empty empty.txt and no nope.txt:
full.txt: ok
empty.txt: empty
nope.txt: missing
The function checks the conditions in order and leaves at the first failure. The readonly variables (lesson 40) cannot be changed by accident. The case statement (lesson 75) turns the status into a message. Each branch reads the same $?, because case $? evaluates it once, before any branch runs.
What Happens with Values Outside 0 to 255
The status is stored in one byte, so other numbers wrap around or fail:
r256() { return 256; }; r256; echo "return 256 -> $?"
r300() { return 300; }; r300; echo "return 300 -> $?"
r255() { return 255; }; r255; echo "return 255 -> $?"
neg() { return -1; }; neg; echo "return -1 -> $?"
txt() { return abc; }; txt; echo "return abc -> $?"
return 256 -> 0
return 300 -> 44
return 255 -> 255
return -1 -> 255
bash: return: abc: numeric argument required
return abc -> 2
A status of 256 becomes 0, which means success, and 300 becomes 44 (300 modulo 256). In Bash 5.2.21, return -1 gave 255 without a message. A non-numeric value is an error with status 2. Stay inside 0 to 255 so that the value means what you wrote. Dash behaves differently: it reported 256 for return 256 and rejected return -1 with Illegal number: -1 (which ended the test script). This is another reason to keep to the 0 to 255 range.
return Leaves the Function Immediately
return ends the function at once, even from inside a loop. This makes a "search" function simple:
find_first_big() {
local n
for n in "$@"; do
if (( n > 100 )); then
echo "found $n"
return 0
fi
done
return 1
}
find_first_big 5 50 500 5000; echo "status $?"
find_first_big 1 2 3; echo "status $?"
found 500
status 0
status 1
The first call stops at 500 and never looks at 5000. The second call finds nothing, the loop ends normally and the last line returns 1. The function reports "found" through the output and the status together, which leads to the next topic.
Getting Output and Status Together
When you capture a function's output with $( ), the status of the substitution is the status of the function, and you can read both:
parse() { echo "parsed:$1"; [ "$1" != "bad" ]; }
out=$(parse good); st=$?
echo "out=[$out] st=$st"
out=$(parse bad); st=$?
echo "out=[$out] st=$st"
out=[parsed:good] st=0
out=[parsed:bad] st=1
Be careful with local. When local and the substitution are on the same line, the status that $? shows is the status of local itself, which is always 0, and the function's status is lost (lesson 48):
get() { echo value; return 7; }
f1() { local r=$(get); echo "local r=\$(get) -> status $?"; }
f1
f2() { local r; r=$(get); echo "split form -> status $?"; }
f2
local r=$(get) -> status 0
split form -> status 7
Declaring the variable first and assigning on the next line keeps the status of get.
return Versus exit
return leaves a function. exit (lesson 118) leaves the whole script, even when it is called inside a function:
quit_now() { echo "leaving"; exit 5; }
quit_now
echo "never printed"
leaving
The script ended with status 5, and the last line did not run. Use return for ordinary functions, so the caller can decide what to do. Use exit only for the code that is allowed to end the program, such as a function that reports a fatal error.
Outside a function, return is an error, unless the file is being run with source:
out90.sh: line 2: return: can only `return' from a function or sourced script
The script continued after that message in the test run (it printed after and ended with status 0). In a file that is run with source (lesson 95), return 3 ends the file early and sets the status of the source command to 3.
Pipelines Inside Functions
The status of a pipeline is the status of its last command (lesson 61). A function that ends with a pipeline therefore reports only that last status, unless pipefail is turned on (lesson 120):
last_only() { false | true; }
last_only; echo "false | true -> $?"
pf() {
set -o pipefail
false | true
local s=$?
set +o pipefail
return $s
}
pf; echo "with pipefail -> $?"
false | true -> 0
with pipefail -> 1
The pf function saves the status in s, turns the option off again and returns the saved value. Restoring the option keeps the change from affecting other code.
Functions, Conditions and set -e
With set -e (lesson 119), the shell ends the script when a command fails. There are exceptions: a command that is used as a condition in if, or on the left side of && or ||, does not trigger it. Functions follow the same rule:
set -e
check() { return 1; }
if check; then echo yes; else echo "check failed, script continues"; fi
check || echo "|| also keeps going"
check
echo "not reached"
check failed, script continues
|| also keeps going
The script ended with status 1 at the plain check line, so not reached was not printed. This difference is why a function that returns a failure status can be a problem in a script with set -e when it is called by itself, but not when its status is tested.
Portability
return N is a POSIX feature and works in Dash. Predicate functions built from [ ] tests, such as is_even() { [ $(( $1 % 2 )) -eq 0 ]; }, work in Dash too. Use the [ ] form there, because (( )) is a Bash feature (lesson 73). Keep the status values within 0 to 255 to get the same result in every shell.