Bash – return a value from shell script, into another shell script

bashshell

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

myfunction could be something like A+B=C

Just echo the result:

$ myfunction() { echo $(($1+$2)); }

The above myfunction adds two numbers and echoes the result.

The return value can then be captured just as you had it:

$ var=$(myfunction 12 5)
$ echo $var
17

The construct var=$(myfunction) captures the standard out from myfunction and saves it in var. Thus, when you want to return something from myfunction, just send it to standard, like we did with echo 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:

$ f() { echo "output1" ; echo "output2" ; }
$ f
output1
output2

If you want to get those values back separately, the most reliable method is to use bash's arrays:

$ a=($(f))

The above executes f, via $(f) and saves the results in an array called a. We can see what is in a by using declare -p:

$ declare -p a
declare -a a='([0]="output1" [1]="output2")'