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

11

我最近在工作中需要大量使用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

你可以在这里找到答案。 - Floris
3个回答

13

不,Bash在函数中除了数值型退出状态之外不会返回任何其他内容。您可以选择以下几种方法:

  1. 在函数内设置非本地变量。
  2. 使用echoprintf或类似命令提供输出。然后可以使用命令替换在函数外分配该输出。

9
你如何在不将字符串作为结果的一部分传递的情况下输出它们? - qodeninja
如果您有一个名为foo的函数,您可以运行result=$(foo) - mrash

8
为了让它只出现在屏幕上,你可以将echo重定向到stderr:
echo "This appears only on the screen" >&2

显然,不应该重定向stderr。

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接