← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 5 of 13

Return Values

A function's return is more like a thumbs up or thumbs down than a gift. It gives back a small success-or-failure number, so if you want real answers you have to have the function print them.

In this page:

  1. Return Values
Syntax
bash
function_name() {
  commands
  return status_code
}
function_name
echo "$?"

Return Values

return in a Bash function sets its exit status (0-255), similar to how a script itself exits — it does *not* return arbitrary data like a return value in other languages.

To "return" a computed value, functions typically echo it and have the caller capture it with $(function_name). Omitting return makes the function's exit status that of its last executed command.

Warning: return values are limited to integers 0–255 — you cannot return a string or a large number directly.

Example: Return Values

bash
#!/bin/bash
is_even() {
    if (( $1 % 2 == 0 )); then
        return 0
    else
        return 1
    fi
}

add() {
    echo $(( $1 + $2 ))
}

if is_even 4; then
    echo "4 is even"
fi

sum=$(add 3 5)
echo "Sum: $sum"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to return a string with return, when it only returns an exit status from 0 to 255.
  2. Capturing output with $(func) and forgetting anything printed becomes the result.
  3. Checking $? too late, after another command has run.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.