我正在运行RHEL 6,我已经导出了一个环境变量,如下所示:

export DISPLAY=:0

当终端关闭时,该变量将丢失。我如何永久地添加这个,以便这个变量值始终存在于特定的用户?


将这一行添加到.bashrc文件或.profile文件中。

在$HOME/文件中设置的变量。配置文件对当前用户是活动的,而/etc/profile中的配置文件是全局的。每次Bash会话启动时都会拉出.bashrc文件。


你可以把它添加到你的shell配置文件中,例如$HOME/。Bashrc或更全局的/etc/environment。

添加这些行之后,更改不会立即反映在基于gui的系统中。您必须退出终端或创建一个新的终端,并在服务器上注销会话并重新登录以反映这些更改。


在Ubuntu系统上,使用以下位置:

格式为“JAVA_PATH=/usr/local/java”的系统级持久化变量存储在 /etc/environment 系统范围的持久变量,引用变量,如 export PATH="$JAVA_PATH:$PATH /etc/.bashrc 格式为“PATH DEFAULT=/usr/bin:usr/local/bin”的用户持久化变量存储在 ~ / .pam_environment

有关#2的更多细节,请查看这个 问Ubuntu答案。

注意:#3是Ubuntu的推荐,但是在现实世界中它可能有安全问题。


一个特别的例子:

我有Java 7和Java 6安装,我需要运行一些构建与6,其他人与7。因此,我需要动态地更改JAVA_HOME,以便Maven为每个构建选择我想要的内容。我做了以下事情:

创建j6.sh脚本,导出JAVA_HOME=…安装j6的路径… 然后,正如上面的一条评论所建议的那样,每当我需要J6进行构建时,我就在相应的命令终端中运行源J6 .sh。默认情况下,我的JAVA_HOME设置为J7。


设置永久环境变量需要编辑三个文件,如下所示:

~/.bashrc When you open any terminal window this file will be run. Therefore, if you wish to have a permanent environment variable in all of your terminal windows you have to add the following line at the end of this file: export DISPLAY=0 ~/.profile Same as bashrc you have to put the mentioned command line at the end of this file to have your environment variable in every login of your OS. /etc/environment If you want your environment variable in every window or application (not just terminal window) you have to edit this file. Add the following command at the end of this file: DISPLAY=0 Note that in this file you do not have to write export command

通常情况下,您必须重新启动计算机才能应用这些更改。但是你可以通过以下命令在bashrc和profile中应用更改:

$ source ~/.bashrc
$ source ~/.profile

但是对于/etc/environment,你别无选择,只能重新启动(据我所知)

一个简单的解决方案

我已经为这些过程编写了一个简单的脚本来完成所有这些工作。您只需设置环境变量的名称和值。

#!/bin/bash
echo "Enter variable name: "
read variable_name
echo "Enter variable value: "
read variable_value
echo "adding " $variable_name " to environment variables: " $variable_value
echo "export "$variable_name"="$variable_value>>~/.bashrc
echo $variable_name"="$variable_value>>~/.profile
echo $variable_name"="$variable_value>>/etc/environment
source ~/.bashrc
source ~/.profile
echo "do you want to restart your computer to apply changes in /etc/environment file? yes(y)no(n)"
read restart
case $restart in
    y) sudo shutdown -r 0;;
    n) echo "don't forget to restart your computer manually";;
esac
exit

将这些行保存在shfile中,然后使其可执行并运行它!


如果适合任何人,这里有一些永久添加环境变量的简单指南。

vi ~/.bash_profile

将变量添加到文件中:

export DISPLAY=:0
export JAVA_HOME=~/opt/openjdk11

立即应用所有更改:

source ~/.bash_profile

来源:如何在Linux中设置环境变量