繁体   English   中英

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

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

我有一个shell函数,该函数访问并触摸全局数组,该数组基本上是一个缓存。 它通过回显返回值:

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
}

如果我以标准方式调用

myValue=$( get_value "foo" )

它不起作用,因为该函数中的cache[]更新发生在子外壳程序( $( ... ) )中,并且在返回脚本又称为父外壳程序时丢失。

我唯一能想到的就是使用全局变量( 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

有更好的选择吗?

使用Bash 4.2.45。

您可以将要向其分配结果的变量名称作为参数传递给函数,然后使用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

如果要控制变量作用域,则最好将value变量设置为局部变量,为什么不这样做,则要使某种main()函数将所有变量保持局部变量(甚至是cache )。

暂无
暂无

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

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