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

Jos*_*osh 22 sudo environment-variables

我正在尝试运行一个需要安装 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看到 java 目录的情况下运行此脚本时;当我运行脚本时sudo它是空白的。

任何想法为什么会发生这种情况?

我正在运行 CentOS。

dog*_*ane 31

出于安全原因,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.
Run Code Online (Sandbox Code Playgroud)

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

Defaults   env_keep += "JAVA_HOME"
Run Code Online (Sandbox Code Playgroud)

或者,设置JAVA_HOME在 root 的~/.bash_profile.

  • 是的,就是这样。没想到有人能做到。谢谢! (2认同)

小智 25

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