在bash函数中打印echo和返回值

mkc*_*zyk 11 bash

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

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

echo $(( $(fun1) + 3 ))
Run Code Online (Sandbox Code Playgroud)

我只能打印回声:

function fun1() {
    echo "Start function"
}

fun1
Run Code Online (Sandbox Code Playgroud)

或者我只能返回值:

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

echo $(( $(fun1) + 3 ))
Run Code Online (Sandbox Code Playgroud)

但我不能两者兼得。

Isk*_*tvo 8

好吧,根据您的意愿,有几种解决方案:

  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 ))
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将消息正常打印到stdout并使用实际返回值$?
    请注意,返回值将始终是来自0- 255(感谢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 ))
    
    Run Code Online (Sandbox Code Playgroud)
  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 ))
    
    Run Code Online (Sandbox Code Playgroud)

  • 我不建议使用选项#2 —— 返回值是一个 1 字节的整数,这意味着它总是在 0 - 255 的范围内。如果你尝试返回 256,你会得到 0。尝试返回 -1,您将得到 255。返回值的真正目的是表示成功(零)与失败(非零),试图将它用于其他任何事情都会导致混淆。 (3认同)