Friday, April 19, 2013

JAVA_HOME annoyances on Linux (Ubuntu)

Just a quick writeup about an annoyance I come across every time I need to use Java on a Linux server. In my case I use the Ubuntu (12.04) server distro, so I'm unsure as to how this behaves on the other distro's. However, setting up the correct JAVA_HOME environment variable for a user never seems automatically done by the system or the package installers.

Tired of manually keeping track of the correct JAVA_HOME environment, I wrote this little script that is called in profile.d at logon time. It simply checks the /etc/alternatives/java symlink and resolves it. Then cuts of the /bin/java and optionally the /jre to construct the JAVA_HOME path. I know for sure that on some systems or in some situations this will not suffice, but on my system it does.

Put the following code in a file in /etc/profile.d (e.g. /etc/profile.d/

# Resolve link

# Test if it is set
  # Test if the full path to java binary ends with /bin/java
  if [[ $INSTALLED_JAVA_ALTERNATIVES =~ .*/bin/java ]]; then
    if [[ $JAVA_HOME_CANDIDATE =~ .*/jre ]]; then

    # Verify JVM
    if [[ -x ${JAVA_HOME_CANDIDATE}/bin/java ]]; then
      # Set the candidate as HOME
When I happen to change the default Java JVM through the provided Ubuntu commands, this piece of scripting will make sure that the JAVA_HOME is correctly updated as well (after the next login). The script is very defensive, so if something isn't returned as expected then it will simply stop and not set a JAVA_HOME at all. Also, a user can still manually override the JAVA_HOME in his private profile.

As always, feel free to throw in a comment. The script is provided as-is and if your head explodes because of it, then don't blame me :)

No comments:

Post a Comment