Returning Status Codes from Functions

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 90 of 205

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:

StatusUsual meaning
0Success
1A general failure
2Wrong usage, for example missing or invalid arguments
126, 127Command found but not executable, command not found
128 + NThe 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.

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 Returning Status Codes from Functions and get answers drawn from it.

Signed-in readers only.