Overwrite and restore environment variables in bash with environment modules

1.1k Views Asked by At

An environment variable that is overwritten in an environment module with the setenv command is unset when unloading the module. In the documentation it is stated that environment variables can be restored, but no method is provided.

I tried using conditional execution, but the following module (~/privatemodules/test) fails to restore an environment variable FOO.

#%Module########################################################################
##
## test modulefile
##
  proc ModulesHelp { } {
  puts stderr "This module modifies an environment variable FOO."
}

module-whatis "Modify environment varible FOO"

if { [module-info mode load] } {
  setenv ORIGINAL_FOO $::env(FOO)
  setenv FOO "123"
} elseif { [module-info mode unload] } {
  setenv FOO $::env(ORIGINAL_FOO)
  unsetenv ORIGINAL_FOO
}

For instance I get:

$ export FOO=bar
$ module load use.own && module load test
$ echo $FOO
123
$ module unload test
$ echo $FOO

$

Is there a method to restore the original value of FOO.

1

There are 1 best solutions below

0
gkaf On

The solution is found in the documentation. The unsetenv takes an extra parameter to set the environment variable to a new value. So the module file should be:

#%Module########################################################################
##
## test modulefile
##
  proc ModulesHelp { } {
  puts stderr "This module modifies an environment variable FOO."
}

module-whatis "Modify environment varible FOO"

if { [module-info mode load] } {
  setenv ORIGINAL_FOO $::env(FOO)
  setenv FOO "123"
} elseif { [module-info mode unload] } {
  unsetenv FOO $::env(ORIGINAL_FOO)
}

This changes in version 5.