使用sudo运行时未在脚本中设置JAVA_HOME


19

我正在尝试运行一个需要安装Java并设置JAVA_HOME环境变量的安装脚本。

我已经设置好了JAVA_HOME/etc/profile并且还在一个我已调用的文件java.sh/etc/profile.d。我可以echo $JAVA_HOME并获得正确的回应,我甚sudo echo $JAVA_HOME至可以并获得正确的回应。

install.sh我要运行的中,我插入了echo $JAVA_HOME。当我不运行此脚本时,会sudo看到j​​ava目录;当我运行脚本时sudo它是空白的。

任何想法为什么会这样?

我正在运行CentOS。


我在运行Ubuntu 14.04时也遇到了这个问题,两个建议的答案都对我
有用

Answers:


28

出于安全原因,sudo可以清除环境变量,这就是为什么它可能不选择$ JAVA_HOME的原因。在/etc/sudoers文件中查找env_reset

来自man sudoers

env_reset   If set, sudo will reset the environment to only contain the following variables: HOME, LOGNAME, PATH, SHELL, TERM, and USER (in addi-
           tion to the SUDO_* variables).  Of these, only TERM is copied unaltered from the old environment.  The other variables are set to
           default values (possibly modified by the value of the set_logname option).  If sudo was compiled with the SECURE_PATH option, its value
           will be used for the PATH environment variable.  Other variables may be preserved with the env_keep option.

env_keep    Environment variables to be preserved in the user's environment when the env_reset option is in effect.  This allows fine-grained con-
           trol over the environment sudo-spawned processes will receive.  The argument may be a double-quoted, space-separated list or a single
           value without double-quotes.  The list can be replaced, added to, deleted from, or disabled by using the =, +=, -=, and ! operators
           respectively.  This list has no default members.

因此,如果您希望它保留JAVA_HOME,请将其添加到env_keep中:

Defaults   env_keep += "JAVA_HOME"

或者,将其设置JAVA_HOME为root ~/.bash_profile


2
是的,就是这样。不知道有人能做到这一点。谢谢!
乔什(Josh)

20

使用-E(保留环境)选项运行sudo(请参阅手册文件),或将JAVA_HOME放入install.sh脚本中。


-E选项在CentOS中不可用。
祖宾
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.