2

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?

2 Answers2

1

The "unexpected" behavior is because of subshell creation with `` or $() at this line.

var=`set_cache`

When the subshell kicks off, it creates it's own variable called v_cache, sets it to 1, and echo's 1 back to set var in the parent shell. Then the subshell exits, and you echo v_cache (of the oringal/parent shell), which is unset.

There are different trains of thought with function, from my background and languages, you should never use a function to change a global, you should instead have it return a value for the global. In this case, change your var to v_cache. Other people (who must have a different background than me) feel this is a short coming of bash.

SaintHax
  • 1,875
  • 11
  • 16
0

If you call function.sh by ./function.sh in test.sh, a sub shell will be launched to run funtion.sh, so the variable value will not be kept in the shell which test.sh is running.

You should call function.sh by source ./function.sh to run them in the same shell.

gzh
  • 3,507
  • 2
  • 19
  • 23
  • `.` (used in the question) and `source` behave identically in bash. Questioner didn't write `./function.sh` they wrote `. function.sh`. – Julian Mar 30 '16 at 14:24
  • @Julian, thx for your comment, I have not known the syntax of . function.sh in shell script by now, i will investigate it. – gzh Mar 30 '16 at 14:31