Bash Function How to Return Value

Bash Function How to Return Value

Bash functions have “return” statement, but it only indicates a return status (zero for success and a non-zero value for failure).

function myfunc() {
var='some text'
echo Hello..
return 10
}

myfunc
echo "Return value of previous function is $?"

Output: Hello.. Return value of the previous function is 10

If you want to return value you can use a global variable.

var=0
string () {
var="My return value."
}
string; echo $var

Output: My return value.

It is simple, but using global variables in complex scripts or programs causes harder methods to find and fix bugs.

We can use command substitution and assign an output from function:

string () {
local local_var="Value from function."
echo $local_var
}

var=$( string )
echo $var

Output: Value from function.

It’s good practice to use within-function local variables. Local variables are safer from being changed by another part of the script.

Leave a Comment