在 Bash 函数中打印回显并返回值

在 Bash 函数中打印回显并返回值

我想在函数中打印回显并返回值。但它不起作用:

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

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

我只能打印回声:

function fun1() {
    echo "Start function"
}

fun1

或者我只能返回值:

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

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

但我无法同时做到这两点。

答案1

嗯,这取决于你的愿望,有几种解决方案:

  1. 将消息打印到stderr以及您希望接收的值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. 将消息正常打印到stdout并将实际返回值与一起使用$?
    请注意,返回值始终是来自的值0- 的值255(感谢戈登·戴维森)。

    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. 只需使用全局变量。

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

答案2

带有附加变量(通过“引用”):

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

fun1 result
echo $(( result + 3 ))

答案3

A有趣的分辨率可以是尾随最后一行fun1()作为返回值:

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

相关内容