Print echo and return value in bash function

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

Tags:

Bash