Return Values
In this page:
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
🔒
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