Understanding return vs. echo in Functions
A Bash function has two separate ways to send something back to the code that called it. The return command sets the function's exit status, a small number from 0 to 255 that says whether the function succeeded. The echo command (or printf) writes data to standard output, and the caller collects that data with command substitution, $( ). The two channels do different jobs, and most confusion about Bash functions comes from using one where the other was needed.
In many programming languages, return hands a value back to the caller: return a + b gives the caller the sum. Bash has no such mechanism. Lesson 90 showed that return N only sets a status. When a Bash function needs to produce a result such as a number, a file name or a line of text, it prints the result, and the caller captures the printed text.
The Two Channels Side by Side
return | echo / printf | |
|---|---|---|
| What it carries | An exit status, 0 to 255 | Any text, any length |
| Meaning | Success (0) or a kind of failure (1 to 255) | The function's result data |
| How the caller reads it | $?, or directly in if, while, &&, || | result=$(function_name args) |
| Ends the function | Yes, immediately | No, the function keeps running |
Returning Data with echo
The usual way to get a value out of a function is to print it and capture it:
add() {
echo $(( $1 + $2 ))
}
sum=$(add 3 4)
echo "sum is $sum"
Output:
sum is 7
Here is what happens step by step:
$(add 3 4)runs the functionaddwith the arguments3and4.- Inside the function,
$(( $1 + $2 ))computes 7 (lesson 49), andechowrites7followed by a newline to standard output. - Command substitution (lesson 48) collects everything the function wrote to standard output, removes the trailing newline, and puts the text
7in place of$(add 3 4). - The assignment stores that text in
sum.
If you call the function without $( ), nothing is captured, and the output goes straight to the terminal:
add 10 20
30
This is useful for functions whose whole purpose is to display something, but a result that the script needs to keep must be captured.
Why return Is the Wrong Tool for Data
It is tempting to write add with return, because that looks like other languages:
add_r() {
return $(( $1 + $2 ))
}
add_r 3 4; echo "3+4 via return: $?"
add_r 200 100; echo "200+100 via return: $?"
3+4 via return: 7
200+100 via return: 44
The first call seems to work. The second shows the problem: an exit status is stored in one byte, so 300 wraps around to 44 (300 minus 256). There are other problems too. A status cannot hold text, negative numbers or decimals, and a function that "returns" 0 is reporting success, not the number zero, so if add_r 0 0 takes the success branch for the wrong reason. Keep return for success and failure, and print the data.
Using Both Channels Together
The two channels work well together. The function prints its result and uses its status to say whether the result is valid. The caller captures the output and tests the status in the same statement:
get_ext() {
local name=$1
case $name in
*.*) echo "${name##*.}"; return 0 ;;
*) return 1 ;;
esac
}
for f in report.pdf notes README; do
if ext=$(get_ext "$f"); then
echo "$f -> extension '$ext'"
else
echo "$f -> no extension (status $?)"
fi
done
report.pdf -> extension 'pdf'
notes -> no extension (status 1)
README -> no extension (status 1)
The condition ext=$(get_ext "$f") is an assignment, and the status of an assignment that contains a command substitution is the status of that substitution, which is the status of the function. When the name has a dot, the function prints the text after the last dot (${name##*.}, lesson 54) and returns 0, so the then branch runs and ext holds the extension. When there is no dot, the function prints nothing and returns 1, so the else branch runs. Inside else, $? still holds the status of the condition.
This pattern answers two questions at once: "did it work?" through the status, and "what is the result?" through the output. Lesson 90 showed one exception: local ext=$(get_ext "$f") on one line reports the status of local (always 0), so inside a function declare the variable first and assign it on the next line.
Keeping Messages Out of the Result
Command substitution captures everything the function writes to standard output. A progress message printed with a plain echo becomes part of the result:
bad_sq() {
echo "computing square of $1"
echo $(( $1 * $1 ))
}
r=$(bad_sq 5)
echo "r=[$r]"
r=[computing square of 5
25]
The variable now holds two lines, and any arithmetic with it would fail. Send messages for the person running the script to standard error with >&2 (lesson 59). Standard error is not captured by $( ), so it still appears on the terminal while the result stays clean:
good_sq() {
echo "computing square of $1" >&2
echo $(( $1 * $1 ))
}
r=$(good_sq 5)
echo "r=[$r]"
computing square of 5
r=[25]
The rule is simple: in a function whose output is meant to be captured, standard output carries only the result, and everything else goes to standard error.
Command Substitution Runs in a Subshell
When a function runs inside $( ), it runs in a subshell, a copy of the current shell. Variable changes made by the function happen in the copy and disappear when the copy ends:
count=0
bump() {
count=$((count + 1))
echo "$count"
}
v=$(bump)
echo "captured $v, count is still $count"
bump >/dev/null
echo "direct call: count is now $count"
captured 1, count is still 0
direct call: count is now 1
Inside the subshell, count became 1 and was printed, so v is 1. The real count was never touched. When the function is called directly, without $( ), it runs in the current shell and the change stays. A function that must both change variables and produce a result should therefore not be called through $( ); it can store its result in a variable instead, as shown later in this lesson.
Each $( ) also costs a little time, because the shell has to create the subshell. This does not matter for a few calls, but in a loop with thousands of iterations the variable-based methods below are faster.
Details of Captured Output
Command substitution removes all trailing newlines, not only the last one:
lines() { printf 'a\nb\n\n\n'; }
x=$(lines)
printf '[%s]\n' "$x"
[a
b]
Newlines inside the text are kept; only the ones at the very end are dropped. This is almost always what you want, because a result like 7 arrives without the newline that echo added.
A second detail concerns echo itself. If the data begins with a dash, echo may treat it as an option:
show() { echo "$1"; }
show2() { printf '%s\n' "$1"; }
v=$(show -n); echo "echo gives [$v]"
v=$(show2 -n); echo "printf gives [$v]"
echo gives []
printf gives [-n]
echo "-n" took -n as its "no newline" option and printed nothing. printf '%s\n' prints its argument exactly (lesson 30). When a function returns data that comes from users, files or other commands, printf '%s\n' "$value" is the safer way to print it.
Returning Several Values
A function can print several values, and the caller can split them. For values on one line, read assigns them to separate variables:
minmax() {
local min=$1 max=$1 n
for n in "$@"; do
(( n < min )) && min=$n
(( n > max )) && max=$n
done
echo "$min $max"
}
read -r lo hi < <(minmax 7 3 9 1 5)
echo "lo=$lo hi=$hi"
out=$(minmax 4 8 2)
read -r lo hi <<< "$out"
echo "lo=$lo hi=$hi"
lo=1 hi=9
lo=2 hi=8
The first form feeds the function's output to read through process substitution, < <( ) (lesson 151). The second captures the output first and passes it with a here string (lesson 64). Both keep lo and hi in the current shell. A pipe, minmax 7 3 9 | read -r lo hi, would not work, because the read at the end of a pipeline runs in a subshell (lesson 61).
For a list of values that may contain spaces, print one value per line and read the lines into an array with mapfile (arrays are covered in lessons 97 to 101):
list_users() { printf '%s\n' alice bob "carol smith"; }
mapfile -t users < <(list_users)
echo "${#users[@]} users; third is '${users[2]}'"
3 users; third is 'carol smith'
Returning Data Without echo
Printing and capturing is the standard method, but Bash offers two other ways to hand back data. Both avoid the subshell, so the function can also change other variables.
A global variable. The function stores its result in an agreed variable name:
to_upper() { result=${1^^}; }
to_upper hello
echo "result=$result"
result=HELLO
This is fast, but the caller has to know the variable name, and a second call overwrites the first result. Lesson 93 shows how such a shared name can clash with a variable of the caller.
A variable name passed by the caller. The caller chooses the name, and the function writes to it. printf -v NAME stores formatted text in the named variable instead of printing it:
pad() { printf -v "$1" '%05d' "$2"; }
pad id 42
echo "id=$id"
id=00042
For more general assignments, a name reference created with local -n (Bash 4.3 or later) makes a local name an alias for the caller's variable:
split_name() {
local -n first_ref=$1 last_ref=$2
first_ref=${3%% *}
last_ref=${3#* }
}
split_name fn ln "Ada Lovelace"
echo "first=$fn last=$ln"
first=Ada last=Lovelace
Inside the function, assigning to first_ref assigns to fn, and assigning to last_ref assigns to ln. Choose reference names that callers are unlikely to use. If the caller passes the same name as the reference itself, Bash detects a loop:
setval() { local -n ref=$1; ref="set by function"; }
setval ref
t91b.sh: line 1: local: warning: ref: circular name reference
t91b.sh: line 1: warning: ref: circular name reference
t91b.sh: line 1: warning: ref: circular name reference
In the test, the value was still stored in the global ref, but only after these warnings. Unusual names such as first_ref or _out make the clash unlikely.
Choosing the Right Channel
| You want to tell the caller... | Use |
|---|---|
| Whether the function succeeded, or yes or no | return (status) |
| A number, a string, a path or a list | echo or printf, captured with $( ) |
| A result, and whether it is valid | Both: print the result, return the status |
| A result, while also changing shell variables | printf -v or local -n with a caller-chosen name |
| A message for the person at the terminal | echo ... >&2 |
Portability
Printing a result and capturing it with $( ), and returning a status with return, work the same in POSIX shells such as Dash:
add() { echo $(( $1 + $2 )); }
sum=$(add 3 4)
echo "sum is $sum"
get() { echo value; return 7; }
v=$(get); echo "v=$v st=$?"
Run with dash, this printed sum is 7 and v=value st=7. The other techniques are Bash features: ${1^^}, printf -v, mapfile, <<< and < <( ) do not exist in Dash, and local -n was rejected with local: -n: bad variable name. In a script that must run under sh, use the print-and-capture method (lessons 188 and 189 cover portable scripts).