With a little side of applesauce...

Monday, May 5, 2008

BASH - export environment variable to parent shell

Interesting... To export an environment variable to a parent shell, you need to source the file, not just export the variable in a script. ie:

speeves@hk:~/scripts$ ./x.sh 
speeves@hk:~/scripts$ echo $authtoken

speeves@hk:~/scripts$ . ./x.sh
speeves@hk:~/scripts$ echo $authtoken
hello world

export authtoken="hello world"


Anonymous said...

No important information.

Anonymous said...

good to know. thanks for sharing :)

other ways to tinker with the parents environment are quite complicated. this method doesnt actually changes the _parent_, it gets executed INSIDE the parent... so there is basically no child or parent.

(is that correct?)

speeves said...

According to the BASH Prompt HOWTO, http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x237.html

sourcing a file acts as if the command were printed on the command line. My expectation would be that an export, (which is used to make variables from children available to parents), would also work in this case. It seems pretty esoteric, but it would be interesting to hear from a real BASH guru that could explain what is happening here :)

Anonymous said...

export is used to make variables from parent known to its children, not the other way around.

And sourcing the file by '.' does not spawn a child shell but the scripts gets executed in the current shell.