bash function how to return value

Answer

Bash functions have "return" statement, but it only indicates a return status (zero for success and 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 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 method 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 script.

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.