可以在不使用echo或全局变量的情况下从Bash函数返回字符串吗?

Rig*_*reM 5 bash interactive return function echo

我在工作中回到了很多Bash脚本,我生锈了.

有没有办法从函数返回本地值字符串而不使其全局或使用echo?我希望函数能够通过屏幕与用户交互,但也可以将返回值传递给变量而不需要像export return_value="return string".printf命令似乎完全像echo一样响应.

例如:

function myfunc() {
    [somecommand] "This appears only on the screen"
    echo "Return string"
}

# return_value=$(myfunc)
This appears only on the screen

# echo $return_value
Return string
Run Code Online (Sandbox Code Playgroud)

小智 9

要使其仅出现在屏幕中,您可以重定向echo到 stderr:

echo "This appears only on the screen" >&2
Run Code Online (Sandbox Code Playgroud)

显然,stderr 不应该被重定向。


Tod*_*obs 8

否.Bash不会从函数返回除数字退出状态之外的任何内容.你的选择是:

  1. 在函数内设置一个非局部变量.
  2. 使用echo,printf或类似提供输出.然后可以使用命令替换在函数外部分配该输出.

  • 如果没有作为结果的一部分传递,你如何"回显"字符串? (3认同)

小智 5

作为该函数的创造性使用eval,您还可以在函数体内将值分配给参数位置,并有效地分配给您的参数。这有时被称为“按输出调用”参数。

foo() {
    local input="$1";
    # local output=$2;  # need to use $2 in scope...

    eval "${2}=\"Hello, ${input} World!\""
}


foo "Call by Output" output;

echo $output;
Run Code Online (Sandbox Code Playgroud)