3

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Make sure that whatever commands you are running, though, aren't expected to modify your current environment. (Which is to say, make sure you aren't sourcing any shell scripts inside the (...).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.