How to change JAVA_HOME with a Bash script

bashenvironment-variables

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

Best Answer

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.