I have a shell function, which accesses and touches a global array, which is basically a cache. 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.
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:
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.