Print echo and return value in bash function

I want print echo in function and return value. It's not working:

function fun1() {
    echo "Start function"
    return "2"
}

echo $(( $(fun1) + 3 ))

I can only print echo:

function fun1() {
    echo "Start function"
}

fun1

Or I can only return value:

function fun1() {
    echo "2" # returning value by echo
}

echo $(( $(fun1) + 3 ))

But I can't do both.


Well, depending on what you wish, there are several solutions:

  1. Print the message to stderr and the value you wish to take in stdout.

    function fun1() {
        # Print the message to stderr.
        echo "Start function" >&2
    
        # Print the "return value" to stdout.
        echo "2"
    }
    
    # fun1 will print the message to stderr but $(fun1) will evaluate to 2.
    echo $(( $(fun1) + 3 ))
    
  2. Print the message normally to stdout and use the actual return value with $?.
    Note that the return value will always be a value from 0-255 (Thanks Gordon Davisson).

    function fun1() {
        # Print the message to stdout.
        echo "Start function"
    
        # Return the value normally.
        return "2"
    }
    
    # fun1 will print the message and set the variable ? to 2.    
    fun1
    
    # Use the return value of the last executed command/function with "$?"
    echo $(( $? + 3 ))
    
  3. Simply use the global variable.

    # Global return value for function fun1.
    FUN1_RETURN_VALUE=0
    
    function fun1() {
        # Print the message to stdout.
        echo "Start function"
    
        # Return the value normally.
        FUN1_RETURN_VALUE=2
    }
    
    # fun1 will print the message to stdout and set the value of FUN1RETURN_VALUE to 2.
    fun1
    
    # ${FUN1_RETURN_VALUE} will be replaced by 2.
    echo $(( ${FUN1_RETURN_VALUE} + 3 ))
    

With additional variable (by "reference"):

function fun1() {
    echo "Start function"
    local return=$1
    eval $return="2"
}

fun1 result
echo $(( result + 3 ))