1
$ function sum()
> {
> echo $1 $2;
> return $(($1+$2))
> }
$ sum 1 2
1 2
$ x=$(sum 1 2)
$ echo $x
1 2

I really expect $x to be 3. But still seems it's the "echo" result. How to fix my function?

Troskyvs
  • 7,537
  • 7
  • 47
  • 115

1 Answers1

1

Don't use return. Just echo the sum as:

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

Then use it as:

x=$(sum 1 2)
echo $x

3

return (or exit) value from a function is captured using $? after calling the function. However using return is not recommended as you can only return 0-255 integer values in a function.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Just for completeness and since 3 it is in range 0-255 it would worth to be mentioned that "return" will be used for the exit code of the function, and could be caught by $? – George Vasiliou Mar 22 '17 at 08:18
  • One can also `echo` _and_ explicitly `return` the value. – arkascha Mar 22 '17 at 08:26