1

I have created a Bash script with the following line:

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home" 2> bash_errors.txt

I have also made the file executable

chmod 777 bash_test

When I run the script and check

java -version
java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.65-b01, mixed mode)

However if I run directly in Bash

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home"

And then check

java -version
java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.75-b04, mixed mode)

The path changes. Furthermore, if I change the script line to

sudo export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home" 2> bash_errors.txt

I get the following in the bash_errors.txt file

sudo: export: command not found

So I know the script is executing, but JAVA_HOME doesn't change when executed from script.

What am I not understanding? How do I change the JAVA_HOME environment variable from a script?

My goal is to permanently change JAVA_HOME from 8 to 7 - I am eventually going to add .bash_profile to my default directory.

Edit

Trying to change files mentioned in linked reference are read only, even using sudo vim:

enter image description here

2

When you are executing a script, you are creating a new process off the interactive shell that lives for the length of your script.

By default this child process inherits your interactive shell environment, and you can alter/modify it. So the contents of the JAVA_HOME environment is altered in the child process, but the child process can't affect the environment of the parent process in your interactive shell.

You can setup the environment for your interactive shell in various places depending on the shell (~/.bash_profile is one for bash as you alluded to in your question). See the linked answer in the comment to your question for the best way to 'permanently set' environment values.

  • While you answered my question - I still cannot update JAVA_HOME permanently. All files mentioned in reference link are READ ONLY in Mac El Capitan. No luck updating permanently in other words. – Roy Hinkley Dec 10 '15 at 17:29
  • You will have to edit them as root (i.e. sudo vim /etc/profile) – jmhindle Dec 10 '15 at 18:11
  • I tried - they are read only files, even using sudo vim. – Roy Hinkley Dec 10 '15 at 18:12
  • 1
    Right - the permissions are read only. sudo can change permissions (using sudo chmod) or you can edit it (with sudo vim /etc/profile) - ignore the warning and write your changes with ':w!'. – jmhindle Dec 10 '15 at 18:23

You must log in to answer this question.

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