Setting JAVA_HOME on Ubuntu

Written on December 31, 2008 by Allan Lykke Christensen

A thing that always annoys me about installing Java is that it doesn’t automatically set up the JAVA_HOME environment variable after installation. I guess this is to avoid having problems when you have multiple virtual machines installed. Anyway, I use Ubuntu Linux to host the majority of my Java Application Server. It is easy install Java (sudo apt-get install sun-java6-jdk) but there always seems to be a debate about where to set the JAVA_HOME environment variable. Some instructions say you should add it to your personal profile (e.g. ~/.bashrc) others suggest adding it to the global profile (i.e. /etc/profile), some people even suggest adding it directly in the init script for the services that need the variable. My suggest is to add an executable shell script to /etc/profile.d/ called javahome.sh. The content of the file would be: export JAVA_HOME=/usr/lib/jvm/java-6-sun. All shell scripts (i.e. executable files with the extension .sh) located in the /etc/profile.d/ directory are loaded upon login and would therefore work for all users without having to change system files that may change upon the next O/S upgrade. To test the script simply type source /etc/profile This will reload the profile for the current user. To verify that the environment variable has been initialised type export|grep JAVA_HOME

Enjoy!

If you enjoyed this post Subscribe to our feed

3 Comments on “Setting JAVA_HOME on Ubuntu”

  1. Stephen |

    Nice tip, but it’s also worth noting that your /etc/profile must explicitly run the scripts in /etc/profile.d/

    At the end of my /etc/profile I put;

    for script in /etc/profile.d/*.sh ; do
    if [ -r $script ] ; then
    . $script
    fi
    done

  2. Allan Lykke Christensen |

    That’s right. Actually on Ubuntu Linux, this is already in /etc/profile by default.

  3. joshis |

    Thank you for the tips!

    I believe there is also a file /etc/environment where you can set environmental variables – you can add JAVA_HOME variable there too.

    If you just want to quickly reconfigure your java environment on ubuntu, note that there is also a command ‘update-java-alternatives’ (that works well at least with the java platforms installed via package system):

    http://blogs.sun.com/pc/entry/easy_way_to_set_your

Leave a Reply

Spam Protection by WP-SpamFree