I have a set of scripts that share some environment variables that are used as status flags.
Consider:
./script1.sh; ./script2.sh; # I execute 2 scripts within the same shell.
Now each of these scripts executes the below script at regular intervals that sets (refreshes) the environment variables:
. ./setEnvVariables.sh #This executes it in the context of the current shell
and thus making the environment variables accessible across both scripts.
script1.sh,script2.sh,..
scripts execution.Another approach would be to have the flags saved in a file and create typical get/set functions to read the file and return/set the flag value. These flags are set by me to simplify controlling the scripts functionality.
Is there a better way of handling this? This kinda falls in the getter-setter design pattern...
If you are using ksh93, not ksh88, a more elegant way would be to implement this using discipline functions.
They allow to implement getter et setters functions for shell variables. You might then create a getter that would pick the variable value from a shared storage area (a file, an ldap directory, a database, whatever) and a setter that would update the same back-end.
Here is a quick example:
a.ksh
function shared.get
{
.sh.value=$(</tmp/shared)
}
function shared.set
{
echo ${.sh.value}>/tmp/shared.new
mv /tmp/shared.new /tmp/shared
}
set -x
echo $shared
shared=22
echo $shared
./b.ksh
echo $shared
b.ksh
function shared.get
{
.sh.value=$(</tmp/shared)
}
function shared.set
{
echo ${.sh.value}>/tmp/shared.new
mv /tmp/shared.new /tmp/shared
}
set -x
echo $shared
shared=11
echo $shared
b.ksh running as subshell modifies the value of the shared variable in the parent process (a.ksh).
$ ./a.ksh
+ echo 11
11
+ shared=22
+ echo 22
22
+ ./b.ksh
+ echo 22
22
+ shared=11
+ echo 11
11
+ echo 11
11