一、环境变量的设置:
/etc/profile:
为用户设置系统环境信息的文件,用户登录时被执行,并从/etc/profile.d目录下配置文件中搜集shell的设置,profile文件的修改对每个用户都生效。profile文件生效的方式:重启电脑/source profile。
/etc/bashrc、/etc/bash.bashrc:
为每一个运行bash shell的用户执行此文件.当bash shell被打开时,该文件被读取。bash.bashrc文件修改对每个用户都生效,生效方式:打开一个shell(在终端输入bash)即可,或者在终端上输入$source bash.bashrc。
~/.bashrc :
在每个用户下都会存在这些文件,功能类似于 /etc/bashrc /etc/bash.bashrc,但只对当前用户生效,生效方式:打开一个shell(在终端输入bash)/在终端上输入$source bash.bashrc。
~/.bash_profile:
每个用户都可使用该文件输入专用于自己使用的shell信息,当用户登录时,该文件仅仅执行一次!默认情况下,他设置一些环境变量,执行用户的.bashrc文件。生效方式:重启电脑/source profile。
~/.bash_logout:
当每次退出系统(退出bash shell)时,执行该文件.
注意事项:在自己的目录下~/的配置文件只有.bashrc/.bash_profile而没有.bash.bashrc /.profile,尽量将环境变量加入到.bash_profile中,否则有可能重新开启shell时,环境变量不会生效。
二、终端登录的方式:
login的shell:
当bash以login shell启动时,他会执行/etc/profile->调用/etc/profile.d目录下所有的脚本,然后执行~/.profile,~/.profile调用~/.bashrc,最后~/.bashrc又调用/etc/bash.bashrc。
非login的shell:
当以非login方式启动时,它会调用~/.bashrc,随后~/.bashrc中调用/etc/bashrc,最后/etc/bashrc调用所有/etc/profile.d目录下的脚本。
验证的方式:
在~/.bash_profile中设置如下变量:
lshell="login shell will see this message"
分别启动一个交互式non-login shell和交互式login shell,查看lshell变量:
[sw@gentoo ~]$ bash
[sw@gentoo ~]$ echo $lshell
[sw@gentoo ~]$ exit
exit
[sw@gentoo ~]$ bash --login
[sw@gentoo ~]$ echo $lshell
login shell will see this message
[sw@gentoo ~]$ exit
logout
login shell与非login shell方式登录:
1、登录系统时获得的顶层shell,无论是通过本地终端登录,还是通过网络ssh登录。这种情况下获得的login shell是一个交互式shell。
2、在终端下使用--login选项调用bash,可以获得一个交互式login shell。
3、在脚本中使用--login选项调用bash(比如在shell脚本第一行做如下指定:#!/bin/bash --login),此时得到一个非交互式的login shell。
4、使用"su -"切换到指定用户时,获得此用户的login shell。如果不使用"-",则获得non-login shell。
su [-lm] [-c 命令] [username],选项与参数:
- :单纯使用 - 如『 su - 』代表使用 login-shell 的变量文件读取方式来登陆系统; 若使用者名称没有加上去,则代表切换为 root 的身份。
-l :与 - 类似,但后面需要加欲切换的使用者账号!也是 login-shell 的方式。
-m :-m 与 -p 是一样的,表示『使用目前的环境配置,而不读取新使用者的配置文件』
-c :仅进行一次命令,所以 -c 后面可以加上命令!
我们应该使用su -、su - root或者su -l root以login shell方式切换至root用户,而不是su或者su root以non-login shell方式切换至root用户。
本文详细介绍了Linux系统中环境变量的配置文件,包括/etc/profile、/etc/bashrc、~/.bashrc和~/.bash_profile的作用及生效方式。同时,讲解了login shell与非login shell的登录方式及其区别,强调了在切换用户至root时应使用login shell方式以加载完整的环境配置。

997


被折叠的 条评论
为什么被折叠?



