How to Return Value from Function in Bash Script
echo inside the function to output the value and capture it with command substitution like result=$(my_function). Alternatively, use global variables or the return statement for exit codes (0-255).Syntax
In Bash, functions return values by printing output with echo. You capture this output outside the function using command substitution. The return statement is used only for exit status codes (0-255), not for returning data.
function_name() { commands; echo value; }- prints the valueresult=$(function_name)- captures printed valuereturn n- sets exit status (integer 0-255)
my_function() {
echo "Hello"
return 0
}
result=$(my_function)
echo "$result"Example
This example shows a function that calculates the sum of two numbers and returns the result by printing it. The caller captures the output using command substitution.
sum() {
local a=$1
local b=$2
echo $((a + b))
}
result=$(sum 5 7)
echo "Sum is: $result"Common Pitfalls
Many beginners try to use return to send back values like in other languages, but in Bash it only sets the exit status (0-255). Trying to return strings or large numbers with return will cause errors or unexpected results.
Always use echo to output values and capture them with command substitution. Also, avoid using global variables unless necessary, as they can cause side effects.
wrong_return() {
return "Hello"
}
# This will cause an error or unexpected behavior
correct_return() {
echo "Hello"
}
result=$(correct_return)
echo "$result"Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Return value | Use echo inside function | Outputs value to capture |
| Capture output | Use result=$(function_name) | Stores function output in variable |
| Exit status | Use return n with 0-255 | Indicates success or error code |
| Avoid | Using return for strings or large numbers | Causes errors or truncation |