使用 /etc/profile.d 而不是 /etc/profile 来配置 Linux 环境变量

在 /etc/profile 这个文件中有这么一段 shell,会在每次启动时自动加载 profile.d 下的每个配置:

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

/etc/profile.d 和 /etc/profile 的区别:

  1. 都用来设置环境变量

  2. /etc/profile.d/ 高度解耦,比 /etc/profile 好维护,不想要什么变量直接删除 /etc/profile.d/ 下对应的 shell 脚本即可

  3. /etc/profile 和 /etc/profile.d 同样是登录(login)级别的变量,当用户重新登录 shell 时会触发,所以效果一致

  4. 设置登录级别的变量后,应重新登录 shell,或者 source /etc/profile 使配置生效

posted @ 2022-12-06 11:16  HopeLive  阅读(93)  评论(0)    收藏  举报