Maven: Java_Home Is Not Defined Correctly

I've installed and configured Maven and Java. I can successfully run

mvn spring-boot:run

But when I run

sudo mvn spring-boot:run

I am getting Maven: JAVA_HOME is not defined correctly

When I do

$ echo $JAVA_HOME
/home/ubuntu/jdk1.8.0_26

Am I missing something here?

1 Answer

You will probably want to edit your sudoers file with sudo visudo, find the line Defaults env_reset and add a line Defaults env_keep = "JAVA_HOME" below it. See below for explanation, details, and alternatives.

Why sudo Is Clearing JAVA_HOME

When you run a command with sudo, by default your environment is not passed intact. Most environment variables are removed, for security, and this is usually desirable. As man sudoers says, in the section on "Command environment":

Since environment variables can influence program behavior, sudoers provides a means to restrict which variables from the user's environment are inherited by the command to be run. There are two distinct ways sudoers can deal with environment variables.

By default, the env_reset option is enabled. This causes commands to be executed with a new, minimal environment. On AIX (and Linux systems without PAM), the environment is initialized with the contents of the /etc/environment file. The new environment contains the TERM, PATH, HOME, MAIL, SHELL, LOGNAME, USER, USERNAME and SUDO_* variables in addition to variables from the invoking process permitted by the env_check and env_keep options. This is effectively a whitelist for environment variables.

If, however, the env_reset option is disabled, any variables not explicitly denied ....

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.