I would like to be able to save my current environment in a file (for a running interactive session), so that I can:
- Save it, export/modify/delete variables at will in the running session, then restore the saved environment
- Switch at will between multiple environment
- Detect differences between two environment
I am only interested in exported variables. As I want to be able to restore the environment it have to be a shell function, I am using bash. Ideally, it would not depends on external programs, and would work on versions of bash from v3.2.25 to current.
For now, to save my environment I use the following function:
env_save () {
export -p > "$STORAGE/$1.sh"
}
That I use as env_save <filename>
in a running session. I have some boilerplate code to keep backups, but let's ignore that.
However, I then have difficulties with loading the environment back:
env_restore () {
source "$STORAGE/$1.sh"
}
As this would not remove spurious variables that I created in the mean time. That is, calling export -p
after env_restore <filename>
might not give the same output than cat $STORAGE/$1.sh
.
Is there a clean way to handle that problem? I will probably need to blacklist some variables such as PWD, OLDPWD, SHELL, SHLVL, USER, SSH_*, STORAGE, etc... That is, those variable should not be saved and should not be changed when restoring as they are special variables. I cannot use a whitelist as I do not know what variables will be there.
export
command is a shell builtin that, as far as I know, is not well suited to your use. You want may want something simpler like env(1), which does not interact with your shell.