What's the system wide way to get java_home Ubuntu?

581    Asked by AlexanderCoxon in Java , Asked on Oct 10, 2022

 I wonder whether Ubuntu itself provides a system-wide way to find the current JAVA_HOME or whether there is a right place for setting JAVA_HOME.


Mac OS X does well in this, for /usr/libexec/java_home command returns the current JAVA_HOME. But on Ubuntu, the materials I found always told me to set the $JAVA_PATH pointing to a static path, which is stored in ~/.bash_profile.


I think, however, this approach has several drawbacks:


Once Java updates, the mini version number will change, which makes the static path no longer available.

After changing the JRE used in my system with update-alternatives, I have to modify $JAVA_HOME in .bash_profile. That extra work is annoying.

Some $JAVA_HOME-required programs are not aware of .bash_profile at all. I have to set $JAVA_HOME in their start-up script, therefore a standard-and-easy way to get $JAVA_HOME seems critical to me.


Answered by Aishwarya Jhadav

The accepted solution byuser13742 assumes that the server definitely has Java installed. In case you're adding this to a centralized script for many servers it will give some errors like:


dirname: missing operand

Try 'dirname --help' for more information.

To avoid that and only set JAVA_HOME Ubuntu if the server has a Java environment, a slight enhancement is:

if [ -f "$(which javac)" ]; then

    export JAVA_HOME=$(dirname $(dirname $(readlink -e $(which javac))))

fi

I also incorporated the change from SimonB to use which to find where the installation is.



Your Answer

Interviews

Parent Categories