Contents

Linux环境变量

Contents

Linux环境变量分登录和非登陆两种,登录的会加载/etc/的环境变量,不登录的话只加载家目录的环境变量,之前用的Ubuntu都是在/etc/environment,而RedHat系列的话都是在/etc/profile下面。

登陆Shell下:

1
2
3
4
#RedHat
/etc/profile --> /etc/profile.d/*.sh --> ~/.bash_profile --> ~/.bashrc --> /etc/bashrc
#Deb系
/etc/profile --> /etc/bash.bashrc --> /etc/profile.d/*.sh --> ~/.profile --> ~/.bashrc

Deb系列里面:/etc/profile会先加载/etc/bash.bashrc,然后再加载/etc/profile.d/*.sh,而RedH系列是只加载/etc/profile.d/*.sh和/etc/profile.d/sh.local

 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
#/etc/profile
if [ "${PS1-}" ]; then
  if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; 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

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

非登陆Shell下:

1
2
3
4
#RedHat
~/.bashrc --> /etc/bashrc --> /etc/profile.d/*.sh
#Deb系
/etc/bash.bashrc --> ~/.bashrc

RedHat中/etc/bashrc和/etc/profile这个判断不一样,里面会做判断$PS1,就是是否是登陆Shell,如果不是的话,也会加载 /etc/profile.d/*.sh,但是会将输出结果输出至/dev/null,所以这个执行判断的时候会让人感觉好像profile.d下面的sh文件没有执行,因为echo的东西都到/dev/null里面了。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    #/etc/profile
    for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then
            . "$i"
        else
            . "$i" >/dev/null
        fi
    fi
done
#/etc/bashrc
    for i in /etc/profile.d/*.sh; do
        if [ -r "$i" ]; then
            if [ "$PS1" ]; then
                . "$i"
            else
                . "$i" >/dev/null

其实查看当前的环境变量最简单的就是分别远程ssh和登录到机器以上执行下echo $PATH就知道配置的环境变量有没有生效了,注意ssh之后的面了用单引号包裹,要不然查看的是本机的哦。

1
2
ssh $host 'echo $PATH'
echo $PATH

所以说在配置环境变量时,如果保证能远程ssh非登陆执行,对于RedHat系,可以通过/etc/profile.d/*.sh来加载,而Deb系列智能/etc/bash.bashrc和~/.bashrc二选一了。

当然了最爱的大蜥蜴Suse的和RedHat很像,如果2024年以后,这个崛起也很好玩的,毕竟Centos太老了,而德国品质的Suse真的是值得拥有。