I am setting my JAVA_HOME
in my ~/.bashrc
file.
Now, I need to create a script that will change the JAVA_HOME
just for the current terminal, so that I can start an app that needs java 5.
I have created this script to do this task, but after finishing, I can see that JAVA_HOME is not updated
export JAVA_HOME=/usr/lib/jvm/java-5-oracle/
export PATH=$PATH:$JAVA_HOME
Here is the result
$ ./javaHome5.sh
$ echo $JAVA_HOME
/usr/lib/jvm/java-6-oracle/
I think that the reason this is not being applied, is that a script is executing in it's own terminal, so when the script ends, the current terminal will not be affected.
Currently, the only way I've found around this is:
- Edit my
~/.bashrc
and change the JAVA_HOME var - Run
source ~/.bashrc
to apply the changes in current terminal. Which again cannot be applied in a script, as thesource
command needs to be run in the current window.
Needless to say, this change applies to all new terminal windows, so I practically need to do this twice: One before starting my app, and one more time right after this, just to restore the environment vars to their default. That's not really convenient.
Do you have any ideas how can I change this var using a script?
Best Answer
It is not possible. As you have correctly observed, your script is executing in its own shell. This shell gets a copy of its parent shell's environment when it is forked, and it has no way to access the parent shell's environment. And that is good, because otherwise scripts could have all kinds of unforeseen side effects. ;)
In order to change variables in your current shell, you can always source your script file (instead of executing it as an independent process), so the script gets executed by your current shell instead of a forked one. If your script is called
myscript.sh
, call it assource myscript.sh
instead of./myscript.sh
.