Bash functions, unlike functions in most programming languages does not allow you to return a value to
The caller. When a bash function ends It return value is it Status:zero for success, Non-zero for failure. To
Return values, can set a global variable with the result, or use command substitution, or you can pass in
The name of a variableto use as the result variable. The examples below describe these different mechanisms.
Although Bash have a return statement, the only thing you can specify with it is the function ' s status, which
is a numeric value as the value specified in an exit statement. The status value is stored in the $? Variable. If
A function does not contain a return statement, it status is set based on the status of the last statement executed
In the function. To actually return arbitrary values to the caller you must use other mechanisms.
The simplest-return a value from a bash function was to just set a global variable to the result. Since
All variables in bash be global by default this is easy:
function MyFunc () {Myresult='some value'}myfunc Echo $myresult
The code above sets the global variable Myresult to the function result. Reasonably simple, but as we all
know, using global variables, particularly in large programs, can leads to difficult to find bugs.
A better approach is to use the local variables in your functions. The problem then becomes how does you get
The result to the caller. One mechanism is to use command substitution:
function MyFunc () {local Myresult='some value'echo'$myresult "}result=$ (myfunc)echo $result
Here the result was output to the STDOUT and the Caller uses command substitution to capture the value
In a variable. The variable can then be used as needed.
Excerpt from:
Returning Values from Bash functions:http://www.linuxjournal.com/content/return-values-bash-functions
Returning Values from Bash Functions