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:
Syntax
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
#!/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 try C/C++/Java/PHP code in the editor
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
- Trying to return a string with
return, when it only returns an exit status from 0 to 255. - Capturing output with
$(func)and forgetting anything printed becomes the result. - Checking
$?too late, after another command has run.
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- Function Basics
- The read Command and Here-Strings
- Function Arguments
- stdin, stdout, stderr and File Descriptors
- Return Values
- Redirection Operators
- Local Variables
- Pipes and Chaining Commands
- Recursive Functions
- Here-Documents (<<EOF)
- Function Libraries
- The tee Command
- Discarding Output with /dev/null