Ubuntu Linux系统包含两类环境变量:系统环境变量和用户环境变量。系统环境变量对所有系统用户都有效,用户环境变量仅仅对当前的用户有效。

修改用户环境变量

用户环境变量通常被存储在下面的文件中:

  • ~/.profile
  • ~/.bash_profile 或者 ~./bash_login
  • ~/.bashrc

上述文件在Ubuntu 10.0以前版本不推荐使用。

系统环境变量

系统环境变量一般保存在下面的文件中:

  • /etc/environment
  • /etc/profile
  • /etc/bash.bashrc

/etc/profile和 /etc/bash.bashrc在Ubuntu 10.0版本中不推荐使用。

加入环境变量

如想将一个路径加入到$PATH中,可以像下面这样做(修改/etc/profile):

1
sudo nano /etc/profile

在里面加入:

1
2
3
4
5
6
JAVA_HOME=/usr/jdk1.6.0_25
export JAVA_HOME
PATH=$PATH:$JAVA_HOME/bin
export PATH
CLASSPATH=.:$JAVA_HOME/lib
export CLASSPATH

你可以自己加上指定的多个路径,中间用冒号隔开。环境变量更改后,在用户下次登陆时生效,如果想立刻生效,则可执行下面的语句:

1
$source /etc/profile

需要注意的是,最好不要把当前路径”./”放到PATH里,这样可能会受到意想不到的攻击。

其他文件的修改方式与此类似,需要注意的是/etc/environment不需要使用export设置环境变量,其他profile文件需要。

更详细的说明可以参考这里

当然如果想使用文本编辑工具修改环境变量,可以使用root权限登录后,直接用文本编辑器打开修改保存

也可以普通用户权限下把文件复制到桌面等修改后用root权限覆盖回去

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
 # and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).
    
 if [ -d /etc/profile.d ]; then
   for i in /etc/profile.d/*.sh; do
     if [ -r $i ]; then
       . $i
     fi
   done
    
 JAVA_HOME=/usr/hadoop/jdk1.6.0_25
 export JAVA_HOME
 PATH=$PATH:$JAVA_HOME/bin
 export PATH
 CLASSPATH=.:$JAVA_HOME/lib
 export CLASSPATH
    
   unset i
 fi
    
 if [ "$PS1" ]; then
   if [ "$BASH" ]; then
     # The file bash.bashrc already sets the default PS1.
     # PS1='\h:\w\$ '
     if [ -f /etc/bash.bashrc ]; then
       . /etc/bash.bashrc
     fi
   else
     if [ "`id -u`" -eq 0 ]; then
       PS1='# '
     else
       PS1='$ '
     fi
   fi
 fi