I have a script with some functions that is loaded in the beginning of other scrips to do the common work. To avoid reprocess, I'm trying to create some kinda cache with some script scope variables. So this is my problem:
supposing I have this scripts:
functions.sh
#!/bin/bash
v_cache=
set_cache()
{
v_cache=1
echo 1
}
echo_cache()
{
echo "v_cache=$v_cache"
}
test.sh
#!/bin/bash
. function.sh
var=`set_cache`
echo_cache
set_cache
echo_cache
Here is the output:
$ ./test.sh
v_cache=
1
v_cache=1
Calling a function in an attribution (either with `func` or $(func)) have different context than a simple call. I need to keep the same scope to all functions calls in the same script (test.sh for example).
For the example above, the output I was expecting is:
$ ./test.sh
v_cache=1
1
v_cache=1
I tried to find some explanation for why it works this way, but can't found nothing. I think `` trigger a new bash execution, completely independent.
There's a way to share a variable through all functions calls? What are the alternatives to bypass this behaviour?