Understanding return vs. echo in Functions

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

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

returnecho / printf
What it carriesAn exit status, 0 to 255Any text, any length
MeaningSuccess (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 functionYes, immediatelyNo, 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:

  1. $(add 3 4) runs the function add with the arguments 3 and 4.
  2. Inside the function, $(( $1 + $2 )) computes 7 (lesson 49), and echo writes 7 followed by a newline to standard output.
  3. Command substitution (lesson 48) collects everything the function wrote to standard output, removes the trailing newline, and puts the text 7 in place of $(add 3 4).
  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 noreturn (status)
A number, a string, a path or a listecho or printf, captured with $( )
A result, and whether it is validBoth: print the result, return the status
A result, while also changing shell variablesprintf -v or local -n with a caller-chosen name
A message for the person at the terminalecho ... >&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).

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 return vs. echo in Functions and get answers drawn from it.

Signed-in readers only.