当前位置: 首页>>技术教程>>正文


在Ubuntu中轻松改变$JAVA_HOME

, , ,

问题描述

在Ubuntu中,我想在Java 5和6之间来回切换我的JAVA_HOME环境变量。

我打开一个终端并输入以下内容来设置JAVA_HOME环境变量:

export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun

在同一个终端窗口中,我键入以下内容以检查环境变量是否已更新:

echo $JAVA_HOME

我看到/usr/lib/jvm/java-1.5.0-sun这是我期待看到的。另外,我修改〜/.profile并将JAVA_HOME环境变量设置为/usr/lib/jvm/java-1.5.0-sun。

现在针对这个问题 – 当我打开一个新的终端窗口并通过键入echo $ JAVA_HOME检查我的JAVA_HOME环境变量时,我看到我的JAVA_HOME环境变量已经恢复为Java 6.当我重新启动我的机器(或日志)时我猜想,JAVA_HOME环境变量设置为Java 5(可能是因为我在〜/.profile中进行了修改)。

有没有办法解决这个问题,以便我可以更改我的JAVA_HOME环境,而无需注销并重新登录(并在所有新的终端窗口中更改环境变量)?

最佳解决方法

将环境变量放入全局/etc/environment文件中:

...
export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun
...

在要更新变量的每个shell中执行“source /etc /environment”:

$ source /etc/environment

检查它是否有效:

$ echo $JAVA_HOME
$ /usr/lib/jvm/java-1.5.0-sun

太棒了,不需要注销。

如果只想在终端中设置JAVA_HOME环境变量,请将其设置在〜/.bashrc文件中。

次佳解决方法

这可能会解决您的问题:https://help.ubuntu.com/community/EnvironmentVariables

Session-wide environment variables

In order to set environment variables in a way that affects a particular user’s environment, one should not place commands to set their values in particular shell script files in the user’s home directory, but use:

~/.pam_environment – This file is specifically meant for setting a user’s environment. It is not a script file, but rather consists of assignment expressions, one per line.

Not recommended:

~/.profile – This is probably the best file for placing environment variable assignments in, since it gets executed automatically by the DisplayManager during the startup process desktop session as well as by the login shell when one logs-in from the textual console.

第三种解决方法

尝试这些步骤。

– 我们要编辑”etc\profile”。环境变量将输入文件的底部。由于Ubuntu不允许访问根文件夹,我们将不得不在终端中使用一些命令

第1步:启动终端。输入命令:gksudo gedit /etc/profile

第2步:配置文本文件将打开。在页面底部输入环境变量………..例如:export JAVA_HOME=/home/alex/jdk1.6.0_22/bin/java

export PATH=/home/alex/jdk1.6.0_22/bin:$PATH

step3:保存并关闭文件。使用echo命令检查环境变量是否设置……..例如echo $PATH

第四种方法

您需要将变量定义放在~/.bashrc文件中。

来自bash手册页:

When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist.

第五种方法

传统上,如果您只想更改终端窗口中的变量,请将其设置为.bashrc文件,该文件在每次打开新终端时都会被提取。每次打开新终端时都不会获取.profile文件。

查看.profile和.bashrc之间的区别:What’s the difference between .bashrc, .bash_profile, and .environment?

.bashrc应该可以解决您的问题。但是,由于您使用的是Ubuntu,因此它不是正确的解决方案。请参阅相关的Ubuntu帮助页面“Session-wide environment variables”。因此,难怪.profile不适合您。我使用Ubuntu 12.04和xfce。我设置了我的.profile,即使我退出也没有生效。类似的经历here。因此您可能必须使用.pam_environment文件并完全忘记.profile.bashrc。请注意,.pam_environment不是脚本文件。

参考资料

本文由Ubuntu问答整理, 博文地址: https://ubuntuqa.com/article/6973.html,未经允许,请勿转载。