Programming
unix environment-variables solaris ksh getter-setter
Updated Sun, 14 Aug 2022 14:13:24 GMT

Environment variables to be used across multiple korn (ksh93) shell scripts (getter-setter)


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.

  • setEnvVariables.sh contains the variables that I want to use in other scripts executed within the same shell.
  • Some of these variables act as flags that may be changed manually in the file during the course of the 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...




Solution

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




Comments (2)

  • +0 – Cool. Didn't know about discipline functions.. I am a newbie when it comes to ksh so will try this and get back to you. Thanks! — Dec 05, 2012 at 16:52  
  • +1 – Very few shell developers know and even less use ksh93 discipline functions. While cool and useful, they aren't enough advertised. One reason is probably due to the fact they aren't in the POSIX standard, the other one would be they are not in bash either. — Dec 06, 2012 at 20:52