代码之家  ›  专栏  ›  技术社区  ›  Rafael

回音和bash中的return有什么区别?[副本]

  •  1
  • Rafael  · 技术社区  · 8 年前

    我知道您可以使用echo在控制台上打印信息。 但我试过用整数来返回,但效果不太好。

    截至

    function echo_test() {
        echo 1;
    }
    
    function output_echo() {
        local result="$(echo_test)";
    
        if [[ ${result} == 1 ]]; then
            echo great;
        else
            echo nope;
        fi
    }
    

    输出“很好”,但是:

    function return_test() {
        return 1;
    }
    
    function output_return() {
        local result="$(return_test)";
    
        if [[ ${result} == 1 ]]; then
            echo great;
        else
            echo nope;
        fi
    }
    

    不起作用。。。输出“不”。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Charles Duffy    8 年前

    你把两件事混为一谈了: 输出 退出状态 .

    echo 产生 输出 . 命令替换,如 $(...) 捕获该输出,但如果在没有它的情况下运行命令,则该输出将转到终端。

    return 退出状态 . 这是用来确定在运行时执行哪个分支的 if your_function; then ... ,或填充 $? .


    去看看你的 return_test 实际上,你可以写下:

    return_test() {
        return 1;
    }
    
    return_test; echo "Exit status is $?"
    

    另外,请注意,可以同时执行以下两种操作:

    myfunc() {
        echo "This is output"
        return 3
    }
    
    myfunc_out=$(myfunc); myfunc_rc=$?
    echo "myfunc_out is: $myfunc_out"
    echo "myfunc_rc is: $myfunc_rc"
    

    …发射:

    myfunc_out is: This is output
    myfunc_rc is: 3
    

    一个有用的习惯用法是把作业放在 if 条件,在捕获输出时分支到退出状态:

    if myfunc_out=$(myfunc); then
      echo "myfunc succeeded (returned 0), with output: [$myfunc_out]"
    else rc=$?
      echo "myfunc failed (nonzero return of $rc), with output: [$myfunc_out]"
    fi
    

    ……在这种情况下,它将返回:

    myfunc failed (nonzero return of 3), with output: [This is output]
    

    顺便说一下,您可能会注意到,当上面的代码捕获 $? 它尽可能地接近正在捕获其退出状态的命令,即使这意味着打破垂直空格周围的常规约定。这是有意的,目的是降低无意中修改添加日志或其他代码更改的可能性 $? 在设定点和使用点之间。

    推荐文章