Issue
I am trying to System.getenv()
to get the value of an environment variable that I have set through my terminal (Mac), I also set the variable in my .bash_profile file and reloaded. After doing so, I echo'd the value and the correct value was printed to the terminal. When trying to retrieve the value of the variable (I made sure I was using the correct name in both my .bash_profile file and when using System.getenv()
.
In the below code, I have replaced the name of the variable with VAR_NAME:
String varValue = System.getenv("VAR_NAME");
System.out.println("Value: " + varValue);
In my .bash_profile:
export VAR_NAME="foo"
"null" is printed when I print out the value of varValue
.
What could be the cause of this?
Edit: I followed the top answer here, restarted Eclipse and it worked!
Solution
The answer to this question is more general than just System.getenv()
in Java.
The environment variables only go down the process tree and only when a process is launched. Eclipse is a child process of your shell (which is also a process) - hence, it inherited all the environment variables 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.
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.
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.There are additional ways to define permanent environment variables. You can take a look here for more information.
Answered By - SomethingSomething