我正在尝试运行一个安装脚本,该脚本需要安装 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。
答案1
出于安全原因,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
使用 -E(保留环境)选项运行 sudo(请参阅 man 文件),或将 JAVA_HOME 放入 install.sh 脚本中。