Introduction
In bash scripts, you use return and echo to send back results from functions. This helps you reuse code and get information from functions.
function_name() {
# Use return to send a number (0-255) as status
return <number>
# Use echo to print text output
echo "some text"
}check_even() {
if (( $1 % 2 == 0 )); then
return 0
else
return 1
fi
}greet() {
echo "Hello, $1!"
}result=$(greet Alice)
echo "$result"#!/bin/bash is_even() { if (( $1 % 2 == 0 )); then return 0 else return 1 fi } say_hello() { echo "Hello, $1!" } number=4 say_hello "User" if is_even $number; then echo "$number is even." else echo "$number is odd." fi
return command inside a function do?return in bash functionsreturn command sends a numeric exit status (0-255) back to the caller, indicating success or failure.echoecho, which prints text output, return only sends a number status, not text.return = numeric status [OK]check?return followed by the number, e.g., return 5.echo 5 prints text, return(status=5) is invalid syntax, and exit 5 exits the whole script.return number syntax [OK]myfunc() {
echo "Hello"
return 3
}
myfunc
echo $? $? after calling it is 3, which is printed next.myfunc() {
return "Success"
}
myfunc
echo $?return must be followed by a numeric status (0-255), not a string.greet that uses echo inside, and store it in a variable msg?echo, use command substitution: $(function_name).msg=$(greet) runs greet and stores its echo output in msg. Other options misuse return or echo.Pass the test and this pattern moves unknown