Cannot locate Java home

Naftuli Kay picture Naftuli Kay · Aug 31, 2012 · Viewed 16.1k times · Source

I'm writing an application that leverages jsvc to start up a Java service as a daemon. I need to use something like jsvc because my application utilizes ports under 1024 and yet I'd really like to not run it as root so that created files are owned by another user. I'd also like to keep dependencies and configuration to a minimum so that all the client needs is a JVM and the jsvc binary installed.

However, it seems that jsvc has one major catch; it can't detect the home folder of Java on a given Unix operating system, which is quite frustrating:

$ ./startup.sh
Cannot locate Java home

I have been able to work around the issue on Ubuntu at least by manually setting the JVM home directory:

jsvc ... -home /usr/lib/jvm/default-java/ ...

Is there any way to determine the Java home directory dynamically from a Bash script so I can make this work across most Unixes/Linuxes? I'd be able to sleep much better at night doing something like:

JAVA_HOME="$( ... )"

jsvc ... -home "$JAVA_HOME" ...

...rather than hard-coding for each individual operating system. Is there a way that, given a java binary, I can find the home directory of its JVM/JRE?

Answer

Naftuli Kay picture Naftuli Kay · Aug 31, 2012

Not sure if this works across *nixes, but found this solution:

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

I've tested it on Ubuntu and it works, however it does not work for OSX.