简体   繁体   中英

System.getenv() returns null when super user

If I run echo $XDG_CURRENT_DESKTOP and sudo echo $XDG_CURRENT_DESKTOP in Ubuntu, I get Unity in both cases. If I in Java write System.getenv("XDG_CURRENT_DESKTOP") , it returns Unity when I run the program without super user privileges but it returns null when I run it with sudo . What is going on here?

public class GetEnv {
        public static void main(String[] args) {
                System.out.println(System.getenv("XDG_CURRENT_DESKTOP"));
        }
}

This is the output:

$ echo $XDG_CURRENT_DESKTOP
$ Unity
$ sudo echo $XDG_CURRENT_DESKTOP
$ Unity
$ javac GetEnv.java
$ java GetEnv
$ Unity
$ sudo java GetEnv
$ null

Because your sudo is wrong.

sudo echo $XDG_CURRENT_DESKTOP

will be expanded to

sudo echo Unity

before executing it as root.

If you want to preserve the setting from the user running sudo you need to define the environment variable which should be preserved in the sudo configuration.

Defaults:suboptimal    env_keep += "XGD_CURRENT_DESKTOP", !requiretty
suboptimal    your_host=NOPASSWD: /user/bin/java

then you could run your command as

sudo java GetEnv

which should show you the setting of the calling user. In your case Unity .

another gotcha with environment variables is not copying them into the super-user's environment (and therefore their value will be null ):

Use the -E flag to do this

sudo -E <command>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM