我想从Bash函数返回一个字符串。

我将用java写这个例子来说明我想做什么:

public String getSomeString() {
  return "tadaa";
}

String variable = getSomeString();

下面的示例可以在bash中工作,但是是否有更好的方法来做到这一点?

function getSomeString {
   echo "tadaa"
}

VARIABLE=$(getSomeString)

当前回答

你可以使用一个全局变量:

declare globalvar='some string'

string ()
{
  eval  "$1='some other string'"
} # ----------  end of function string  ----------

string globalvar

echo "'${globalvar}'"

这给了

'some other string'

其他回答

Bash自2014年2月4.3版(?)起,除了“eval”之外,还明确支持引用变量或名称引用(namerefs),具有相同的性能和间接效果,并且在你的脚本中可能更清晰,也更难“忘记'eval'而不得不修复此错误”:

declare [-aAfFgilnrtux] [-p] [name[=value] ...]
typeset [-aAfFgilnrtux] [-p] [name[=value] ...]
  Declare variables and/or give them attributes
  ...
  -n Give each name the nameref attribute, making it a name reference
     to another variable.  That other variable is defined by the value
     of name.  All references and assignments to name, except for⋅
     changing the -n attribute itself, are performed on the variable
     referenced by name's value.  The -n attribute cannot be applied to
     array variables.
...
When used in a function, declare and typeset make each name local,
as with the local command, unless the -g option is supplied...

还有:

PARAMETERS A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands (see the descriptions of declare and local below) to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is⋅ referenced or assigned to, the operation is actually performed on the variable specified by the nameref variable's value. A nameref is commonly used within shell functions to refer to a variable whose name is passed as an argument to⋅ the function. For instance, if a variable name is passed to a shell function as its first argument, running declare -n ref=$1 inside the function creates a nameref variable ref whose value is the variable name passed as the first argument. References and assignments to ref are treated as references and assignments to the variable whose name was passed as⋅ $1. If the control variable in a for loop has the nameref attribute, the list of words can be a list of shell variables, and a name reference will be⋅ established for each word in the list, in turn, when the loop is executed. Array variables cannot be given the -n attribute. However, nameref variables can reference array variables and subscripted array variables. Namerefs can be⋅ unset using the -n option to the unset builtin. Otherwise, if unset is executed with the name of a nameref variable as an argument, the variable referenced by⋅ the nameref variable will be unset.

例如(EDIT 2:(谢谢你Ron)在函数内部变量名的命名空间(前缀),以最小化外部变量冲突,这最终应该正确地回答了Karsten在评论中提出的问题):

# $1 : string; your variable to contain the return value
function return_a_string () {
    declare -n ret=$1
    local MYLIB_return_a_string_message="The date is "
    MYLIB_return_a_string_message+=$(date)
    ret=$MYLIB_return_a_string_message
}

测试这个例子:

$ return_a_string result; echo $result
The date is 20160817

请注意,bash“declare”内置在函数中使用时,默认情况下会使声明的变量为“local”,并且“-n”也可以与“local”一起使用。

我更喜欢区分“重要的声明”变量和“无聊的本地”变量,因此以这种方式使用“声明”和“本地”作为文档。

编辑1 -(对Karsten下面的评论的回应)-我不能再在下面添加评论了,但Karsten的评论让我思考,所以我做了以下测试,工作良好,AFAICT - Karsten如果你读了这篇文章,请从命令行提供一组准确的测试步骤,显示你假设存在的问题,因为以下步骤工作得很好:

$ return_a_string ret; echo $ret
The date is 20170104

(我刚刚将上面的函数粘贴到bash术语中后运行了这个程序——正如您所看到的,结果运行得很好。)

您还可以捕获函数输出:

#!/bin/bash
function getSomeString() {
     echo "tadaa!"
}

return_var=$(getSomeString)
echo $return_var
# Alternative syntax:
return_var=`getSomeString`
echo $return_var

看起来很奇怪,但比使用全局变量更好。传递参数和往常一样,只是把它们放在大括号或反勾号内。

像上面的bstpierre一样,我使用并推荐使用显式命名输出变量:

function some_func() # OUTVAR ARG1
{
   local _outvar=$1
   local _result # Use some naming convention to avoid OUTVARs to clash
   ... some processing ....
   eval $_outvar=\$_result # Instead of just =$_result
}

注意引用$的用法。这将避免将$result中的内容解释为shell特殊字符。我发现这比result=$(some_func "arg1")捕获回声的习惯用法快一个数量级。在MSYS上使用bash时,速度差异似乎更加显著,从函数调用中捕获标准输出几乎是灾难性的。

可以发送一个局部变量,因为局部变量在bash中是动态作用域的:

function another_func() # ARG
{
   local result
   some_func result "$1"
   echo result is $result
}

如前所述,从函数返回字符串的“正确”方法是使用命令替换。如果函数也需要输出到控制台(如@Mani上面提到的),在函数的开头创建一个临时fd并重定向到控制台。在返回字符串之前关闭临时fd。

#!/bin/bash
# file:  func_return_test.sh
returnString() {
    exec 3>&1 >/dev/tty
    local s=$1
    s=${s:="some default string"}
    echo "writing directly to console"
    exec 3>&-     
    echo "$s"
}

my_string=$(returnString "$*")
echo "my_string:  [$my_string]"

执行没有参数的脚本会产生…

# ./func_return_test.sh
writing directly to console
my_string:  [some default string]

希望这能帮助到人们

安迪

为了说明我对Andy的回答的评论,使用额外的文件描述符操作来避免使用/dev/tty:

#!/bin/bash

exec 3>&1

returnString() {
    exec 4>&1 >&3
    local s=$1
    s=${s:="some default string"}
    echo "writing to stdout"
    echo "writing to stderr" >&2
    exec >&4-
    echo "$s"
}

my_string=$(returnString "$*")
echo "my_string:  [$my_string]"

不过还是很恶心。