Reputation: 62356
I'm trying to set an environmental variable in linux. I followed the instructions here: Make $JAVA_HOME easily changable in Ubuntu
Despite using source /etc/environment
and using echo MY_VAR
to verify that linux detects the variable, my java app will not pick up on it. The variable continues to return null
public static void main(String[] args) throws IOException {
System.out.print(System.getenv("MY_VAR"));
I'm executing my java application via sudo java -jar /path/to/my.jar
Update: My mistake, I hadn't included the correct command. I'm actually sudoing.
Upvotes: 4
Views: 11625
Reputation: 4151
The issue is that sudo runs with it's own set of environment variables. You can either add the variable to the root environment (sometimes finicky), or tell sudo to maintain the current environment's variables explicitly.
Here's how you would do the latter:
vim ~/.bash_profile
export MY_VAR=80
sudo visudo
Defaults env_keep +="MY_VAR"
Now when you run sudo java -jar /path/to/my.jar
it should work as desired, with MY_VAR set to 80.
Upvotes: 1
Reputation: 7335
from the linked answer ..
Execute "source /etc/environment" in every shell where you want the variables to be updated:
When you call java -jar /path/to/my.jar
I think you will be starting a new shell, meaning that the contents of ./etc/environment wont be available to the shell your java code is running in.
try
export MY_ENVIRONMENT="HELLO"
java -jar /path/to/my.jar
Does that look any better?
And if you are sudo -ing your command ...
sudo -c export MY_ENVIRONMENT="HELLO";java -jar /path/to/my.jar
or something along those lines
Upvotes: 1
Reputation: 22973
You need to export the variable
export MY_VAR=stackoverflow
java -jar /path/to/my.jar
then you can print the value with
System.out.print(System.getenv("MY_VAR"));
edit: short example script (amend the path if necessary)
#!/bin/sh
MY_VAR="foobaz not exported"
echo "MY_VAR: ${MY_VAR}"
java -jar my.jar
export MY_VAR="foobaz exported"
echo "MY_VAR: ${MY_VAR}"
java -jar my.jar
Upvotes: 6