Last Updated: February 25, 2016
·
2.524K
· eviweb

Automatically define JAVA_HOME in bash script

copy/paste the following code in your executable bash script

#!/bin/bash
if [ -z "${JAVA_HOME}" ]
then
    JAVA_HOME=$(readlink -nf $(which java) | xargs dirname | xargs dirname | xargs dirname)
    if [ ! -e "$JAVA_HOME" ]
    then
        JAVA_HOME=""
    fi
    export JAVA_HOME=$JAVA_HOME
fi

It will try to retrieve the java home directory if it exists and export the $JAVA_HOME environment variable