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

Return Values

In this page:

  1. Return Values

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"

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.