Freddie Chopin Freddie Chopin - 1 month ago 6
Bash Question

Restore previous value or unset environment variable

I have something like that in a shell script

cd /some/folder1
savedCFLAGS=${CFLAGS-}
export CFLAGS="-fexceptions ${CFLAGS-}"
./configure --some-option -what-ever
make
export CFLAGS=${savedCFLAGS}

cd /some/folder2
./configure --some-option -what-ever
make


This works more or less correctly but has one serious flaw.
If CFLAGS was unset previously, after the first block it will be set and empty.
Sometimes, this is a problem, because some configure scripts use default values for variables only if they are actually unset - default value will not be used if the variable is simply empty.

Let me also state that I have such constructs multiple times in the script, with multiple different variables(this is a script used to build complete GCC-based toolchain).

What would be the easiest way to have the variable either restored to previous value (if it actually was set previously) or unset (if it was unset before my modifications)?
I could set
savedCFLAGS
to some special token if it was unset, and then test whether
savedCFLAGS
has a value equal to that token.
However, maybe there's something much simpler?

Answer

Just run your setenv+configure+make in a subshell using parentheses:

(export CFLAGS="-fexceptions ${CFLAGS-}";./configure --some-option -what-ever; make)

It inherits the environment in a copy, so when exiting the sub-shell you get the exact same "previous" state: no env. variables are ever changed in your script, and further configure commands work properly.