java 找不到 JAVA_HOME 作为 Sudo
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11469247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAVA_HOME not found as Sudo
提问by anotherdave
I have a bash script on a Linux box that runs a Jar file. When logged in as a regular user I don't have permission to run the script, but it prints the following log:
我在运行 Jar 文件的 Linux 机器上有一个 bash 脚本。以普通用户身份登录时,我无权运行该脚本,但它会打印以下日志:
*INFO * Using JVM found at /opt/jdk6/bin/java
When I try to use the script with Sudo though, it gives:
但是,当我尝试将脚本与 Sudo 一起使用时,它给出:
*ERROR* Unable to locate java, please make sure java is installed and JAVA_HOME set
I've set JAVA_HOME
to the same path above — can see it with echo $JAVA_HOME
& it's also set as an option within the script. I'm happy that the script isn't the issue — it's a default CQ5 control script & I'm using it on dozens of other boxes without issue. Just unsure what I'm doing wrong above & presume it's something I'm missing re Linux set-up?
我已经设置JAVA_HOME
为与上面相同的路径 - 可以用echo $JAVA_HOME
&看到它,它也被设置为脚本中的一个选项。我很高兴脚本不是问题——它是一个默认的 CQ5 控制脚本,我在其他几十个盒子上使用它没有问题。只是不确定我在上面做错了什么并假设这是我在 Linux 设置中遗漏的东西?
When I run the sudo
command, does it have access to the JAVA_HOME
that I set up as myself?
当我运行sudo
命令时,它是否可以访问JAVA_HOME
我自己设置的?
回答by fork0
By default, sudo
will cleanup the environment of the spawned commands. Pass -E
to keep it:
默认情况下,sudo
将清理生成的命令的环境。通过-E
保持它:
sudo -E env
Compare to:
相比于:
sudo env
回答by Danke Xie
"sudo -E " didn't solve the problem when JAVA_HOME was not exported. And when it was exported, "sudo " without -E works the same.
当 JAVA_HOME 未导出时,“sudo -E”没有解决问题。当它被导出时,没有 -E 的“sudo”的工作原理是一样的。
So you can add export JAVA_HOME=.../jdk<version>
in your .bash_profile and .bashrc file.
所以你可以添加export JAVA_HOME=.../jdk<version>
你的 .bash_profile 和 .bashrc 文件。
In case you wondered what's the difference of .bash_profile and .bashrc, .bash_profile is executed upon login (e.g., show some diagnostic/welcome information). .bash_rc is executed when you open a new terminal (e.g., shift-ctrl-T).
如果您想知道 .bash_profile 和 .bashrc 的区别是什么,.bash_profile 在登录时执行(例如,显示一些诊断/欢迎信息)。.bash_rc 在您打开新终端(例如,shift-ctrl-T)时执行。
In order to run some commands for both cases, you can put it in .bashrc file, and let .bash_profile source .bashrc:
为了在这两种情况下运行一些命令,你可以把它放在 .bashrc 文件中,并让 .bash_profile 源 .bashrc:
if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi
回答by thouliha
You could always just pass it to java explicitly like this:
你总是可以像这样明确地将它传递给 java:
sudo java -Djava.home=$JAVA_HOME Test
sudo java -Djava.home=$JAVA_HOME Test