Linux使用profile.d目录设置环境变量

100人浏览   2024-09-01 10:33:12

操作系统:Centos 7.9

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


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

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/profile会执行/etc/profile.d/目录下的所有*.sh文件。

区别

1、都用来设置环境变量文件

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

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

4、设置登录级别的变量,重新登录 shell,或者 source /etc/profile。

在/etc/profile 文件中设置的变量是全局变量,是系统级别的,对所有用户都有效


相关推荐