2.1.1 shell登录解读

学习目标

这一节,我们从 基础知识、简单实践、小结 三个方面来学习。

基础知识

shell配置文件

系统级别生效配置文件
	/etc/profile
		系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行
    /etc/profile.d/*.sh
    	被/etc/profile文件调用,执行当前目录下所有的文件中关于shell的设置
    /etc/bashrc
    	为每一个运行bash shell的用户执行此文件.当bash shell被打开时,该文件被读取。
用户级别生效配置文件
	~/.bash_profile
		设定用户专用的shell信息,当用户登录时,该文件仅仅执行一次
	~/.bashrc
		该文件包含用户专用的bash信息,当登录时以及每次打开新的shell时,该文件被读取
用户退出生效配置文件
	~/.bash_logout: 当每次退出系统(退出bash shell)时,执行该文件.
    ~/.bash_history: 
    	用户登录时自动读取其中的内容并加载到内存hiatory记录中
    	logout时将内存中的history记录写入该文件中

shell的登录方式

交互式登录
    方法1:密码登录
        直接通过终端输入账号密码登录
        复制终端
    方法2:su 变更shell操作用户的身份
        su - 用户名
        超级用户除外,需要键入该使用者的密码。
非交互式登录
	方法1:脚本执行
	方法2:su 用户名
登录shell的文件生效流程
	/etc/profile.d/*.sh
		-> /etc/profile
			-> /etc/bashrc
				-> ~/.bashrc
					-> ~/.bash_profile
非登录shell的文件生效流程
	/etc/profile.d/*.sh
		-> /etc/bashrc
			-> ~/.bashrc 
注意:
	若多配置文件中设置相同的变量,则后面配置文件中变量的值会覆盖前面配置文件中同一变量的值。
su的相关参数
	-:当前用户不仅切换为指定用户的身份,同时所用的工作环境也切换为此用户的环境。
    -l:同 - 的使用类似,完整切换工作环境,后面需要添加欲切换的使用者账号。
    -p:表示切换为指定用户的身份,但不改变当前的工作环境(不使用切换用户的配置文件)。
    -m:和 -p 一样;
    -c 命令:仅切换用户执行一次命令,执行后自动切换回来,该选项后通常会带有要执行的命令。

配置文件修改后生效的方法

修改profile和bashrc文件后需生效两种方法
    1. 重新启动shell进程
    2. source|. 配置文件

注意:
	source 会在当前shell中执行脚本,所有一般只用于执行置文件,或在脚本中调用另一个脚本的场景

简单实践

准备工作

为所有的shell相关的配置文件添加关键信息
echo "echo '1 - /etc/profile'" >> /etc/profile
echo "echo '2 - /etc/profile.d/2.sh'" >> /etc/profile.d/2.sh
echo "echo '3 - /etc/bashrc'" >> /etc/bashrc
echo "echo '4 - ~/.bash_profile'" >> ~/.bash_profile
echo "echo '5 - ~/.bashrc'" >> ~/.bashrc

非登录效果

[root@localhost ~]# su - python
上一次登录:五 6月 10 16:16:37 CST 2022pts/1 上
2 - /etc/profile.d/2.sh
1 - /etc/profile
3 - /etc/bashrc
[python@localhost ~]$ su root
密码:
2 - /etc/profile.d/2.sh
3 - /etc/bashrc
5 - ~/.bashrc
[root@localhost /home/python]# exit
exit

登录查看效果

切换标准root用户
[python@localhost ~]$ su - root
密码:
上一次登录:日 6月 12 12:41:11 CST 2022pts/2 上
2 - /etc/profile.d/2.sh
1 - /etc/profile
3 - /etc/bashrc
5 - ~/.bashrc
4 - ~/.bash_profile

新建终端效果
Last login: Sun Jun 12 12:35:59 2022 from 10.0.0.1
2 - /etc/profile.d/2.sh
1 - /etc/profile
3 - /etc/bashrc
5 - ~/.bashrc
4 - ~/.bash_profile
[root@localhost ~]#

清理环境

将刚才创建的5条命令执行反向操作
[root@localhost ~]# vim ...
	
退出当前shell环境
[root@localhost ~]# exit
登出
Session stopped
    - Press <return> to exit tab
    - Press R to restart session
    - Press S to save terminal output to file

小结