30 November 2015

Although shell is usually not regarded as a language for "serious" programming, there is still needs for saving/loading environment variables between sessions. This is not only feasible but also easier than one might think. The idea is, you write variables into a file in a "source-able" format and then source that file later to load the variables.

The "var=value" way

The most straightforward way might be to just write var_name=var_value into a file, say "./environ". And then source ./envrion to load it in following sessions. For example:

# To save:
echo "var='$var'" > ./environ

# To load
source ./environ

Note that the single quotes around $var are crucial to keep this mechanism work in cases when value of var contains white space.

The biggest problem of this measure, however, is that it does not preserve all attributes and hence can only deal with simple variables. For example, it does not save "readonly" flags.

The "declare -p" way (BASH only) measure

In deed, BASH provides declare -p, which makes the serialization of environment variables a breeze. It prints variables in a source-able format, preserving their attributes. Hence, be they readonly-s, arrays, integers, you just:

declare -p var1 var2 > ./environ # NOTE: no '$' before var1, var2

One caveat for the "declare -p xx", though: if you wrap the source ./environ into a function, then all sourced variables are visible within the function only because declare by default declares variables as local ones. To circumvent this, you may either source out of any function (or in your main function) or add -g (which makes corresponding variable global) to each line of ./environ after exporting. For instance:

declare -p var1 var2
sed -i 's/^declare\( -g\)*/declare -g/' ./environ
# "\( -g\)?" ensure no duplication of "-g"

blog comments powered by Disqus