System.getenv() does not list all the environment

2019-06-23 01:32发布

问题:

I have noticed that some of my environment variables are not being picked up by the JVM.

In my .bash_profile I defined the following:

IO_HOME='some_value'
export IO_HOME

and by doing in shell:

echo $IO_HOME

I get the correct result.

But neither System.getProperties() nor System.getenv() is showing this variable being set. I tried both Java 6 and Java 7.

Is there something I am missing?

回答1:

Exporting environment to spawned processes is pretty stable; if System.getenv() is not including a variable then it is because it is not in the environment. A couple of things to check, both relating to how the process is started:

  • Are you starting the java process from an environment where the variable is exported? For example, if it is in your .bash_profile and you are executing the java program from a menu or desktop then you have to log out and log in after adding it in .bash_profile for your desktop to see the variable.

  • Is the variable explicitly removed from environment for the process? ProcessBuilder allows this, as do most of all APIs that spawn processes.

One thing to try is to start the process from command line shell, after ensuring the variable is exported in that shell.



回答2:

From Windows, I recently saw some crazy behaviour where IntelliJ refused to show all env vars from System.getenv() after setting either user or system env vars. The trick was to launch IntelliJ from a DOS box. For Windows users: Maybe a reboot (or logoff/logon) will fix the issue.