ping localhost
ping localhost

Reputation: 479

Prevent child process from inheriting parent's environment

I have the following 2 scenarios with a command doSomething which runs in the background and uses an env variable VAR. I have assigned the correct value for the variable in ~/.bash_profile.

1) When run from the bash prompt with $doSomething & : Things work fine since the correct value of VAR is used.

2) When run from inside a shell script : The shell script has itself been invoked as part of a process cycle that has altered the value of VAR and exported. When I call $doSomething & inside the shell script, it uses the new value of VAR and fails. That makes sense since the command inherits the environment for the script. Is there a way I can invoke the command such that it uses the values in bash_profile?

It seems that one option could be to use env -u to unset the altered value and reassign the value in bash_profile. Is there a better way?

Thanks !

Upvotes: 2

Views: 1097

Answers (1)

hek2mgl
hek2mgl

Reputation: 157990

I suggest to put the variable definition into a separate file, like:

var.sh

export VAR="value"

Then source that file form inside your .bashrc and from your script:

source /path/to/var.sh

Putting the variable definition into a separate file has the advantage that you don't need to source the whole .bashrc from inside your script which might lead to unwanted side effects.

Upvotes: 0

Related Questions