Shell – how to share environment variables between shells like globals related to a master pid

dynamic-linkingenvironment-variablesshell-script

So, I need to share environment variables between shells, and that the changes on the variables be promptly recognized by all shells, like global variables. But they must be related to a master PID, so I can have 2 shell scripts running, each being a master with same global variable name, and it children will only change the variable related to their master PID.

I use bash for scripting.

My current researches are these:

Modules
I read I could use modules project for that: http://modules.sourceforge.net/, but I am having huge trouble trying to do it, it seems to lack examples? also "modules" is a too generic word, very hard to google about because mixes with many other things… after some weeks my hands are still empty…

Simple text source file
I read also I should use a simple text file to store/update/read variables from, as a source script file, using flock too to avoid concurrent writing. But there are problems related to doing that, like concurrent change of variable simultaneously by 2 shells.

Alternatively
I am aware that after a "global" variable is read by the shell, it will keep that value until another read is made; and another shell may change it in the mean while too…
May be a very fast external application could provide such storage and we would not try to use environment variables as globals then? but my guess is any SQL solution will be too slow…

Best Answer

You can write the environment to a file with export -p and read it back periodically in the other instances with . (the include command). But as you note, if there are concurrent modifications, the result won't be pretty.

If you want modifications to propagate instantly, you'll have to use a wrapper around the export builtin that also propagates the changes to the other shells. On Linux, you can use the flock utility.

global_export () {
  {
    flock 0
    . /path/to/env
    [ $# -eq 0 ] || export "$@"
    export -p >/path/to/env
  } </path/to/env
}

Note that you'll need to call global_export whenever you assign a new value to an exported variable.

This is rather clumsy. It's likely that there's a better way to solve your problem. The most obvious way is to have whatever command is using those environment variable read a configuration files instead.

Related Question