3

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:

  1. Edit my ~/.bashrc and change the JAVA_HOME var
  2. Run source ~/.bashrc to apply the changes in current terminal. Which again cannot be applied in a script, as the source 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?

0

1 Answer 1

9

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 as source myscript.sh instead of ./myscript.sh.

2
  • Thanks, source myscript.sh works nicely, why didn't I think about this? I've also added an alias : alias j5='source ./myscript.sh'
    – yannicuLar
    Jun 9, 2016 at 9:57
  • 2
    You're welcome. :) If you haven't already done so, you might want to use an absolute path in your alias: alias j5='source /absolute/path/to/myscript.sh' so that you can call j5 from anywhere, independently of your current working directory. Jun 9, 2016 at 10:09

Not the answer you're looking for? Browse other questions tagged .