System.getenv() returns null when the environment variable exists [duplicate]

Solution 1:

The answer to this question is more general than just System.getenv() in Java.

Every process has its own independent copy of environment variables, while the environment variables only go down the process tree and are copied from parent to child only when the child process is created. In your case, your shell, which itself is a process, started/created the Eclipse process. Therefore, Eclipse is a child process of your shell and therefore, the environment variables defined on your Eclipse instance are a copy of those that had been defined on your shell when you launched Eclipse.

You probably defined the environment variable on your shell after you had launched Eclipse. Hence, Eclipse and the child Java processes it created, would never "know" about your new environment variable.

Due to this behavior, actually the solution here is to exit Eclipse and launch it again from your shell, in which the environment variable is already defined. Another option is to go to the run configuration of the project and define there the environment variable.

P.S.

  1. Obviously, if you restart your computer, the environment variables you have defined on your shell will not be saved, simply since the shell process you defined the variables on will be gone.

  2. If you use bash, then by adding the environment variable setting command to the file ~/.bashrc, which is executed each time a bash process is started, you can simulate the behavior of permanent environment variables.

  3. There are additional ways to define permanent environment variables. You can take a look here for more information.