How to determine JAVA_HOME on Debian/Ubuntu?

On Ubuntu it is possible to have multiple JVMs at the same time. The default one is selected with update-alternatives. But this does not set the JAVA_HOME environment variable, due to a debian policy.

I am writing a launcher script (bash), which starts a java application. This java application needs the JAVA_HOME environment variable. So how to get the path of the JVM which is currently selected by update-alternatives?


Solution 1:

For the JRE, something like this should do the trick:

JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

Solution 2:

danadam's solution can easily be adopted to retrieve the JDK (i.e. not JRE) path as required:

JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:/bin/javac::")
  • Looks for javac Java compiler (instead of java) included in JDK (but not JRE).
  • Has no trailing / (stripped off by sed s:/bin... instead of s:bin...)

Solution 3:

export JAVA_HOME=$(dirname $(dirname $(readlink -f /usr/bin/java)))

In .bashrc was handy for me.