简体   繁体   English

如何在不创建子Shell的情况下从Shell脚本中的函数调用返回值?

[英]How can I return a value from a function call in a shell script without creating a subshell?

I have a shell function, which accesses and touches a global array, which is basically a cache. 我有一个shell函数,该函数访问并触摸全局数组,该数组基本上是一个缓存。 It returns the value by echoing it: 它通过回显返回值:

declare -A cache

function get_value() {
    if [ ${cache[$1]+exists} ]; then
        echo ${cache[$1]}
    else
        value=$(create_value $1) # want to cache this result
        cache[$1]="${value}"
        echo $value
    fi
}

If I call it in the standard way 如果我以标准方式调用

myValue=$( get_value "foo" )

it does not work because the cache[] update in the function happens in a subshell (the $( ... ) ) and is lost upon returning to the script aka parent shell. 它不起作用,因为该函数中的cache[]更新发生在子外壳程序( $( ... ) )中,并且在返回脚本又称为父外壳程序时丢失。

The only thing I can think of is using a global variable ( result ) for the return value, but of course that's not so great in terms of structured programming: 我唯一能想到的就是使用全局变量( result )作为返回值,但是就结构化编程而言,这当然不是那么好:

declare -A cache

function get_value() {
    if [ ${cache[$1]+exists} ]; then
        result=${cache[$1]}
    else
        value=$(create_value $1) # want to cache this result
        cache[$1]="${value}"
        result=$value
    fi
}

get_value "foo"
myValue=$result

Is there a better alternative? 有更好的选择吗?

Using Bash 4.2.45. 使用Bash 4.2.45。

You can pass the variable name to which you want to assign the result as a parameter to the function, and use printf -v to perform the assignment : 您可以将要向其分配结果的变量名称作为参数传递给函数,然后使用printf -v执行分配:

declare -A cache

function get_value() {
    if [ ${cache[$1]+exists} ]; then
        printf -v "$2" "${cache[$1]}"
    else
        local value=$(create_value "$1") # want to cache this result
        cache[$1]="$value"
        printf -v "$2" "$value"
    fi
}

get_value "foo" my_value

If you are going to control variable scope, you might as well make your value variable local and, why not, make some kind of main() function to keep all variables local (even your cache ). 如果要控制变量作用域,则最好将value变量设置为局部变量,为什么不这样做,则要使某种main()函数将所有变量保持局部变量(甚至是cache )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM