Search code examples
javalinuxshellnullgetenv

Java getenv() returns null


I'm defining an environment variable in a Linux shell with TestEnviron=varproperty. Now, I want to write a small program that reads the environment variable, writes it to the console output, and writes the variable to a properties file. However when I try it with this code getenv() returns null:

package javaenvironmentvariable;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;

public class JavaEnvironmentVariable {
    public static void main(String[] args) {
        try {
            String variable = System.getenv("TestEnviron");
            System.out.println("TestEnviron: " + variable);
            variable = "TestEnviron=" + variable;

            Properties properties = new Properties();

            File file = new File("Variables.properties");
            FileOutputStream fileout = new FileOutputStream(file);
            properties.store(fileout, variable);
            fileout.close();
        } catch (Exception e) {
        }
    }
}

I use this in the shell to call the jar: sudo java -jar JavaEnvironmentVariable.jar


Solution

  • You should use sudo -E AND export to keep the environment variables:

    $ export TestEnviron=varproperty
    $ sudo -E java -jar JavaEnvironmentVariable.jar
    

    However to be more safe you should configure sudo to keep your variable as explained in this post: How to keep Environment Variables when Using SUDO :

    sudo visudo
    

    and add this line:

    Defaults env_keep += "TestEnviron"