Function
Returning Values from Bash Function
Method 1: Simplest
function myfunc()
{
myresult='some value'
}
myfunc
echo $myresultMethod 2: Better approach
function myfunc()
{
local myresult='some value'
echo "$myresult"
}
result=$(myfunc) # or result=`myfunc`
echo $resultMethod 3: Accepts variable
function myfunc()
{
local __resultvar=$1
local myresult='some value'
eval $__resultvar="'$myresult'"
}
myfunc result
echo $resultNOTE: Make sure to use variable names inside the function that are not likely to be used as parameter variable. e.g.
__resultvar.
Method 4: More flexibility
function myfunc()
{
local __resultvar=$1
local myresult='some value'
if [[ "$__resultvar" ]]; then
eval $__resultvar="'$myresult'"
else
echo "$myresult"
fi
}
myfunc result
echo $result
result2=$(myfunc)
echo $result2Ref: