用于在shell脚本中返回多个值的习惯用法

时间:2010-03-21 21:06:28

标签: shell idioms

是否有任何习惯用法从脚本中的bash函数返回多个值?

http://tldp.org/LDP/abs/html/assortedtips.html描述了如何回显多个值并处理结果(例如,示例35-17),但如果返回的某些值是包含空格的字符串,则会变得棘手。

更有条理的返回方式是分配给全局变量,比如

foo () {
    FOO_RV1="bob"
    FOO_RV2="bill"
}

foo
echo "foo returned ${FOO_RV1} and ${FOO_RV2}"

我意识到,如果我需要在shell脚本中重新进行操作,我可能做错了,但我仍然觉得抛出全局变量只是为了保持返回值,感到非常不舒服。

有更好的方法吗?我更喜欢可移植性,但如果我必须指定#!/bin/bash,它可能不是一个真正的限制。

10 个答案:

答案 0 :(得分:12)

您的值永远不会包含空格的特殊情况下,此read技巧可以是一个简单的解决方案:

get_vars () {
  #...
  echo "value1" "value2"
}

read var1 var2 < <(get_vars)
echo "var1='$var1', var2='$var2'"

但当然,只要其中一个值中有空格,它就会中断。您可以修改IFS并在函数echo中使用特殊分隔符,但结果并不比其他建议的解决方案简单。

答案 1 :(得分:10)

这个问题是5年前发布的,但我有一些有趣的答案发布。我刚刚开始学习bash,我也遇到了和你一样的问题。我认为这个技巧可能会有所帮助:

#!/bin/sh

foo=""
bar=""

my_func(){
    echo 'foo="a"; bar="b"'
}

eval $(my_func)
echo $foo $bar
# result: a b

当子进程无法将值发送回其父进程时,此技巧对于解决问题也很有用。

答案 2 :(得分:8)

就像我喜欢shell一样,可能的情况是,只要你抛出任意结构化数据,Unix bourne / posix shell就不是正确的选择。

如果字段内没有字符,则用其中一个字符分开。经典示例是/etc/passwd/etc/group以及使用冒号作为字段分隔符的各种其他文件。

如果使用可以在字符串内处理NUL字符的shell,那么加入NUL并在其上分离(通过$ IFS或其他)可以很好地工作。但是几个常见的炮弹,包括猛击,打破了NUL。测试将是我的一个旧的.sig:

foo=$'a\0b'; [ ${#foo} -eq 3 ] && echo "$0 rocks"

即使这对您有用,您也只是达到了一个警示标志,即是时候切换到更结构化的语言(Python,Perl,Ruby,Lua,Javascript ......选择您喜欢的毒药)。您的代码可能难以维护;即使你可以,也会有一小部分人能够很好地理解它,以保持它。

答案 3 :(得分:2)

在不支持 nameref (在Bash 4.3-alpha中引入)的Bash版本中,我可以定义辅助函数,其中返回值被赋给给定变量。这有点像使用eval来执行相同类型的变量赋值。

示例1

##  Add two complex numbers and returns it.
##  re: real part, im: imaginary part.
##
##  Helper function named by the 5th positional parameter
##  have to have been defined before the function is called.
complexAdd()
{
    local re1="$1" im1="$2" re2="$3" im2="$4" fnName="$5" sumRe sumIm

    sumRe=$(($re1 + $re2))
    sumIm=$(($im1 + $im2))

    ##  Call the function and return 2 values.
    "$fnName" "$sumRe" "$sumIm"
}

main()
{
    local fooRe='101' fooIm='37' barRe='55' barIm='123' bazRe bazIm quxRe quxIm

    ##  Define the function to receive mutiple return values
    ##  before calling complexAdd().
    retValAssign() { bazRe="$1"; bazIm="$2"; }
    ##  Call comlexAdd() for the first time.
    complexAdd "$fooRe" "$fooIm" "$barRe" "$barIm" 'retValAssign'

    ##  Redefine the function to receive mutiple return values.
    retValAssign() { quxRe="$1"; quxIm="$2"; }
    ##  Call comlexAdd() for the second time.
    complexAdd "$barRe" "$barIm" "$bazRe" "$bazIm" 'retValAssign'

    echo "foo = $fooRe + $fooIm i"
    echo "bar = $barRe + $barIm i"
    echo "baz = foo + bar = $bazRe + $bazIm i"
    echo "qux = bar + baz = $quxRe + $quxIm i"
}

main

示例2

##  Add two complex numbers and returns it.
##  re: real part, im: imaginary part.
##
##  Helper functions
##      getRetRe(), getRetIm(), setRetRe() and setRetIm()
##  have to have been defined before the function is called.
complexAdd()
{
    local re1="$1" im1="$2" re2="$3" im2="$4"

    setRetRe "$re1"
    setRetRe $(($(getRetRe) + $re2))

    setRetIm $(($im1 + $im2))
}

main()
{
    local fooRe='101' fooIm='37' barRe='55' barIm='123' bazRe bazIm quxRe quxIm

    ##  Define getter and setter functions before calling complexAdd().
    getRetRe() { echo "$bazRe"; }
    getRetIm() { echo "$bazIm"; }
    setRetRe() { bazRe="$1"; }
    setRetIm() { bazIm="$1"; }
    ##  Call comlexAdd() for the first time.
    complexAdd "$fooRe" "$fooIm" "$barRe" "$barIm"

    ##  Redefine getter and setter functions.
    getRetRe() { echo "$quxRe"; }
    getRetIm() { echo "$quxIm"; }
    setRetRe() { quxRe="$1"; }
    setRetIm() { quxIm="$1"; }
    ##  Call comlexAdd() for the second time.
    complexAdd "$barRe" "$barIm" "$bazRe" "$bazIm"

    echo "foo = $fooRe + $fooIm i"
    echo "bar = $barRe + $barIm i"
    echo "baz = foo + bar = $bazRe + $bazIm i"
    echo "qux = bar + baz = $quxRe + $quxIm i"
}

main

答案 4 :(得分:2)

另一种方式:

function get_tuple()
{
  echo -e "Value1\nValue2"
}

IFS=$'\n' read -d '' -ra VALUES < <(get_tuple)
echo "${VALUES[0]}" # Value1
echo "${VALUES[1]}" # Value2

答案 5 :(得分:1)

你可以使用关联数组,你有bash 4,例如

declare -A ARR
function foo(){
  ...
  ARR["foo_return_value_1"]="VAR1"
  ARR["foo_return_value_2"]="VAR2"
}

您可以将它们组合为字符串。

function foo(){
  ...
  echo "$var1|$var2|$var3"
}

然后,只要您需要使用这些返回值,

ret="$(foo)"
IFS="|"
set -- $ret
echo "var1 one is: $1"
echo "var2 one is: $2"
echo "var3 one is: $3"

答案 6 :(得分:1)

我会选择解决方案I suggested here,而是使用数组变量。较旧的bash:es不支持关联数组。 例如。,

function some_func() # ARRVAR args...
{
    local _retvar=$1 # I use underscore to avoid clashes with return variable names
    local -a _out
    # ... some processing ... (_out[2]=xxx etc.)
    eval $_retvar='("${_out[@]}")'
}

致电网站:

function caller()
{
    local -a tuple_ret # Do not use leading '_' here.
    # ...
    some_func tuple_ret "arg1"
    printf "  %s\n" "${tuple_ret[@]}" # Print tuple members on separate lines
}

答案 7 :(得分:1)

Bash的更高版本支持 nameref 。使用declare -n var_namevar_name提供 nameref 属性。 nameref 使您的函数能够“通过引用传递”,这在C ++函数中通常用于返回多个值。根据Bash手册页:

  

可以使用声明本地内置的 -n 选项为变量分配 nameref 属性用于创建 nameref 的命令,或对另一个变量的引用。这允许间接操纵变量。每当引用或分配 nameref 变量时,操作实际上是对 nameref 变量的值指定的变量执行的。 nameref 通常在shell函数中用于引用其名称作为参数传递给函数的变量。

以下是一些交互式命令行示例。

示例1:

$ unset xx yy
$ xx=16
$ yy=xx
$ echo "[$xx] [$yy]"
[16] [xx]
$ declare -n yy
$ echo "[$xx] [$yy]"
[16] [16]
$ xx=80
$ echo "[$xx] [$yy]"
[80] [80]
$ yy=2016
$ echo "[$xx] [$yy]"
[2016] [2016]
$ declare +n yy # Use -n to add and +n to remove nameref attribute.
$ echo "[$xx] [$yy]"
[2016] [xx]

示例2:

$ func()
> {
>     local arg1="$1" arg2="$2"
>     local -n arg3ref="$3" arg4ref="$4"
> 
>     echo ''
>     echo 'Local variables:'
>     echo "    arg1='$arg1'"
>     echo "    arg2='$arg2'"
>     echo "    arg3ref='$arg3ref'"
>     echo "    arg4ref='$arg4ref'"
>     echo ''
> 
>     arg1='1st value of local assignment'
>     arg2='2st value of local assignment'
>     arg3ref='1st return value'
>     arg4ref='2nd return value'
> }
$ 
$ unset foo bar baz qux
$ 
$ foo='value of foo'
$ bar='value of bar'
$ baz='value of baz'
$ qux='value of qux'
$ 
$ func foo bar baz qux

Local variables:
    arg1='foo'
    arg2='bar'
    arg3ref='value of baz'
    arg4ref='value of qux'

$ 
$ {
>     echo ''
>     echo '2 values are returned after the function call:'
>     echo "    foo='$foo'"
>     echo "    bar='$bar'"
>     echo "    baz='$baz'"
>     echo "    qux='$qux'"
> }

2 values are returned after the function call:
    foo='value of foo'
    bar='value of bar'
    baz='1st return value'
    qux='2nd return value'

答案 8 :(得分:0)

Shell脚本函数只能返回执行的最后一个命令的退出状态或return语句明确指定的该函数的退出状态。

要返回一些字符串,可以这样:

function fun()
{
  echo "a+b"
}

var=`fun` # Invoke the function in a new child shell and capture the results
echo $var # use the stored result

这可能会减少您的不适,虽然它增加了创建新shell的开销,因此会稍微慢一点。

答案 9 :(得分:0)

我是bash的新手,但是发现此代码有所帮助。

function return_multiple_values() {
        eval "$1='What is your name'"
        eval "$2='my name is: BASH'"
    }
    
    return_var=''
    res2=''
    return_multiple_values return_var res2
    echo $return_var
    echo $res2