I know how to return an exit code, but I would like to return the result of an operation done in a shell script function, so I can eventually use it in another script or function.
Something like
var1=$(myfunction)
function2 var1
Where myfunction could be something like A+B=C
I looked into "return", but it will return a code, not a value.
I am looking into various sites that show how to write functions, but I don't see how you actually return values.
In C++ you would use return "variable name", but shell script won't allow this. It says that the variable do not exist (which is logical, it is a variable created in a function, so when the function is released, that memory space assigned to it is gone). Can't use global variables since the function may be in one script and the calling function that needs the return value, may be in a different one.
Best Answer
Just echo the result:
The above
myfunction
adds two numbers and echoes the result.The return value can then be captured just as you had it:
The construct
var=$(myfunction)
captures the standard out frommyfunction
and saves it invar
. Thus, when you want to return something frommyfunction
, just send it to standard, like we did withecho
in the example above.In cases where you want the return value to be carefully formatted, you should consider using
printf
in place of echo.More: How to return multiple values
Let's define a function that produces two outputs:
If you want to get those values back separately, the most reliable method is to use bash's arrays:
The above executes
f
, via$(f)
and saves the results in an array calleda
. We can see what is ina
by usingdeclare -p
: