Search code examples
linuxbashreturnecho

bash function failed to give a return value


$ 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?


Solution

  • 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.