2017-02-17 62 views
1

我有一個shell函數,它訪問並觸及一個全局數組,它基本上是一個緩存。它呼應它返回值:如何在不創建子shell的情況下從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[]更新發生在子shell(在$(...))和在回到腳本aka父shell時丟失了。

我能想到的唯一的事情就是用返回值一個全局變量(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。

回答

2

你可以通過變量名要結果分配作爲參數的功能,並使用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)。

+0

'create_value'$ 1「',應該是。除此之外,我的異議都受到意見/辯論(即使用不必要的和無用的非功能性'功能'關鍵字)。 –

+0

......哦,我看到從OP複製的錯誤。 –

+0

我應該抓住它,有時我只專注於OP的即時問題。固定。 – Fred

相關問題