What's the system wide way to get java_home Ubuntu?
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.
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.