2

I want to run different versions of Java on the same machine (Linux Mint 17) with default to Java 7. So I put this into /etc/environment:

JAVA_HOME="/tools/java/java7"
JAVA7_HOME="/tools/java/java7"
JAVA8_HOME="/tools/java/java8"

And in /etc/profile:

export PATH="${JAVA_HOME}/bin:...:${PATH}"

I expect java -version to be 8 if JAVA_HOME equals to /tools/java/java8 and 7 if it is set to point to Java 7.

So, I run:

┌[madhead@madhead-mint:~/Projects/thymeleaf]
└─$ export JAVA_HOME=/tools/java/java8 && java -version
java version "1.7.0_60"
Java(TM) SE Runtime Environment (build 1.7.0_60-b19)
Java HotSpot(TM) Server VM (build 24.60-b09, mixed mode)

And

┌[madhead@madhead-mint:~/Projects/thymeleaf]
└─! $ export JAVA_HOME=/tools/java/java7 && java -version
Java(TM) SE Runtime Environment (build 1.7.0_60-b19)
Java HotSpot(TM) Server VM (build 24.60-b09, mixed mode)

No matter what is JAVA_HOME $PATH looks like this:

┌[madhead@madhead-mint:~/Projects/thymeleaf]
└─$ echo $PATH
/home/madhead/bin:/usr/local/bin:/tools/java/java7/bin:...:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

And export JAVA_HOME=/tools/java/java8 && which java outputs /tools/java/java7/bin/java too.

So, it looks like real substitution appears when I log in. Can this behavior be changed? It would be great if I can solve this with env variables, and not with symlinks.

4

You are correct that the substitution occurs when PATH is defined. It is simple to get around that. Define a bash/zsh function:

javaswitch() { [[ "$1" =~ ^[0-9]$ ]] && export  PATH=${PATH/java[0-9]/java$1}; }

Now, anytime that you want to switch java versions, run:

javaswitch 7

Or:

javaswitch 8

To make the definition of javaswitch permanent, place it in your ~/.bashrc file.

How it works

  • [[ "$1" =~ ^[0-9]$ ]]

    For protection against typos, this tests to make sure that the argument is a number. If it isn't, then no change is made.

    If you are sure that you will only use versions 7 or 8, then use instead:

    [[ "$1" =~ ^[7-8]$ ]]
    
  • export PATH=${PATH/java[0-9]/java$1}

    This uses pattern substitution to update PATH to the new version number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.