Ben
Ben

Reputation: 62356

Java not picking up on environmental variable

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

Answers (3)

Kyle Chadha
Kyle Chadha

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:

  1. Open up your bash profile vim ~/.bash_profile
  2. Add the environment variable to the file export MY_VAR=80
  3. Open up the sudoers config file sudo visudo
  4. Add the following line to the file exactly as so 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

DaveH
DaveH

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

SubOptimal
SubOptimal

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

Related Questions