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.

1

3 Answers

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 ))
1

With additional variable (by "reference"):

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

A funny resolution could be tailing the last line of fun1() as a returned value:

function fun1() { echo "Start function" echo "return:" echo "2"
}
# Create a temporary file
output=$(mktemp)
# Run and redirect the output to console and to file simultaneously
fun1 |& tee $output
# Get the last line of the file into returnValue
returnValue=$(tail -1 $output)
echo $(( $returnValue + 3 ))

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like