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

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

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

String variable = getSomeString();

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

function getSomeString {
   echo "tadaa"
}

VARIABLE=$(getSomeString)

当前回答

以上所有答案都忽略bash手册页中所述内容。

函数中声明的所有变量都将与调用环境共享。 所有在本地声明的变量将不会被共享。

示例代码

#!/bin/bash

f()
{
    echo function starts
    local WillNotExists="It still does!"
    DoesNotExists="It still does!"
    echo function ends
}

echo $DoesNotExists #Should print empty line
echo $WillNotExists #Should print empty line
f                   #Call the function
echo $DoesNotExists #Should print It still does!
echo $WillNotExists #Should print empty line

和输出

$ sh -x ./x.sh
+ echo

+ echo

+ f
+ echo function starts 
function starts
+ local 'WillNotExists=It still does!'
+ DoesNotExists='It still does!'
+ echo function ends 
function ends
+ echo It still 'does!' 
It still does!
+ echo

同样在pdksh和ksh下,这个脚本也做同样的事情!

其他回答

为了说明我对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]"

不过还是很恶心。

提醒薇姬·罗嫩,考虑一下下面的代码

function use_global
{
    eval "$1='changed using a global var'"
}

function capture_output
{
    echo "always changed"
}

function test_inside_a_func
{
    local _myvar='local starting value'
    echo "3. $_myvar"

    use_global '_myvar'
    echo "4. $_myvar"

    _myvar=$( capture_output )
    echo "5. $_myvar"
}

function only_difference
{
    local _myvar='local starting value'
    echo "7. $_myvar"

    local use_global '_myvar'
    echo "8. $_myvar"

    local _myvar=$( capture_output )
    echo "9. $_myvar"
}

declare myvar='global starting value'
echo "0. $myvar"

use_global 'myvar'
echo "1. $myvar"

myvar=$( capture_output )
echo "2. $myvar"

test_inside_a_func
echo "6. $_myvar" # this was local inside the above function

only_difference

将会给

0. global starting value
1. changed using a global var
2. always changed
3. local starting value
4. changed using a global var
5. always changed
6. 
7. local starting value
8. local starting value
9. always changed

也许正常的场景是使用test_inside_a_func函数中使用的语法,因此在大多数情况下可以同时使用这两种方法,尽管捕获输出是在任何情况下都能工作的更安全的方法,它模仿在其他语言中可以找到的函数的返回值,Vicky Ronnen正确地指出了这一点。

虽然有很多很好的答案,但它们都不是我想要的方式。下面是我的解决方案,要点如下:

帮助健忘的程序员

至少我会努力记住错误检查之后,像这样:

允许用换行字符\n赋值

有些解决方案不允许这样做,因为有些解决方案忘记了要赋值周围的单引号。正确的方法:eval "${returnVariable}='${value}'"或者更好:参见下面的下一点。

使用printf代替eval

只需尝试使用类似myFunction "date && var2"的东西来解决这里的一些假定的解决方案。Eval会执行给它的任何东西。我只想分配值,所以我使用printf -v "${returnVariable}" "%s" "${value}"代替。

对变量名冲突的封装和保护

如果一个不同的用户或至少是对函数了解较少的人(这可能是几个月后的我)正在使用myFunction,我不希望他们知道他必须使用全局返回值名称或禁止使用某些变量名称。这就是为什么我在myFunction的顶部添加了一个名称检查:

    if [[ "${1}" = "returnVariable" ]]; then
        echo "Cannot give the ouput to \"returnVariable\" as a variable with the same name is used in myFunction()!"
        echo "If that is still what you want to do please do that outside of myFunction()!"
        return 1
    fi

注意,如果你需要检查很多变量,这也可以放在函数本身中。 如果我仍然想使用相同的名称(这里:returnVariable),我只是创建了一个缓冲变量,给myFunction,然后复制值returnVariable。

就是这样:

myFunction ():

myFunction() {
    if [[ "${1}" = "returnVariable" ]]; then
        echo "Cannot give the ouput to \"returnVariable\" as a variable with the same name is used in myFunction()!"
        echo "If that is still what you want to do please do that outside of myFunction()!"
        return 1
    fi
    if [[ "${1}" = "value" ]]; then
        echo "Cannot give the ouput to \"value\" as a variable with the same name is used in myFunction()!"
        echo "If that is still what you want to do please do that outside of myFunction()!"
        return 1
    fi
    local returnVariable="${1}"
    local value=$'===========\nHello World\n==========='
    echo "setting the returnVariable now..."
    printf -v "${returnVariable}" "%s" "${value}"
}

测试用例:

var1="I'm not greeting!"
myFunction var1
[[ $? -eq 0 ]] && echo "myFunction(): SUCCESS" || echo "myFunction(): FAILURE"
printf "var1:\n%s\n" "${var1}"

# Output:
# setting the returnVariable now...
# myFunction(): SUCCESS
# var1:
# ===========
# Hello World
# ===========
returnVariable="I'm not greeting!"
myFunction returnVariable
[[ $? -eq 0 ]] && echo "myFunction(): SUCCESS" || echo "myFunction(): FAILURE"
printf "returnVariable:\n%s\n" "${returnVariable}"

# Output
# Cannot give the ouput to "returnVariable" as a variable with the same name is used in myFunction()!
# If that is still what you want to do please do that outside of myFunction()!
# myFunction(): FAILURE
# returnVariable:
# I'm not greeting!
var2="I'm not greeting!"
myFunction "date && var2"
[[ $? -eq 0 ]] && echo "myFunction(): SUCCESS" || echo "myFunction(): FAILURE"
printf "var2:\n%s\n" "${var2}"

# Output
# setting the returnVariable now...
# ...myFunction: line ..: printf: `date && var2': not a valid identifier
# myFunction(): FAILURE
# var2:
# I'm not greeting!
myFunction var3
[[ $? -eq 0 ]] && echo "myFunction(): SUCCESS" || echo "myFunction(): FAILURE"
printf "var3:\n%s\n" "${var3}"

# Output
# setting the returnVariable now...
# myFunction(): SUCCESS
# var3:
# ===========
# Hello World
# ===========

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术语中后运行了这个程序——正如您所看到的,结果运行得很好。)

agt@agtsoft:~/temp$ cat ./fc 
#!/bin/sh

fcall='function fcall { local res p=$1; shift; fname $*; eval "$p=$res"; }; fcall'

function f1 {
    res=$[($1+$2)*2];
}

function f2 {
    local a;
    eval ${fcall//fname/f1} a 2 3;
    echo f2:$a;
}

a=3;
f2;
echo after:a=$a, res=$res

agt@agtsoft:~/temp$ ./fc
f2:10
after:a=3, res=