login shell和no login shell区别

写在前面的话

这篇文章主要是介绍login shell与no login shell的区别。
这两种shell的区别是在启动和退出时候会执行不同的脚本,进而影响环境变量。

交互式shell与非交互式shell

这里先谈一下交互式shell和非交互式shell,交互式shell即是我们启动一个终端,输入一条命令然后回显结果。也就是我们通常使用的命令行工具都是交互式的。例如下面的就是交互式的一个shell终端。
在这里插入图片描述
而非交互式shell,在这种模式下,shell不与用户进行交互,而是读取存放在文件中的命令,并执行它们,当读取到文件的结尾,shell也就终止执行了。
例如我们新建一个.sh文件,该脚本是需要shell程序解释执行的

#!/bin/bash
echo $$
read name
echo ${name}

在这里插入图片描述
该var_shell.sh脚本是bash执行的,然而当这个脚本执行结束以后,该bash就会结束执行了.
在这里插入图片描述
如下:
在这里插入图片描述
刚才6455进程及即bash已经退出了.在这里插入图片描述

login shell与no login shell

A login shell is one whose first character of argument zero is a -, or one started with the --login option.

即login shell是第0个参数是一**-**字符开头的,或者启动shell时指定–login参数即bash --login,这样启动的shell就是login shell。

  When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

  When a login shell exits, bash reads and executes commands from the files ~/.bash_logout and /etc/bash.bash_logout, if the files exists.

  When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.

也就是说当一个login shell被调用的时候,会首先加载/etc/profile,然后去用户家目录下按顺序查找~/.bash_profile, ~/.bash_login, and ~/.profile这三个文件,按照这个顺序找到哪个文件就加载该文件,当该login shell退出时,会执行~/.bash_logout and /etc/bash.bash_logout这两个文件的内容,如果某一个文件不存在就执行一个就可以了.

对于no login shell来说,则是在被调用的时候加载执行~/.bashrc文件里的命令

下面是我在ubuntu18.04.1系统上的测试结果
在这里插入图片描述
首先我们发现远程通过ssh连接后第一个字符是**-,也就是所谓的login shell了,
在这里插入图片描述
而对于我们直接在终端打开的却是
no login shell**
在这里插入图片描述
你可能会疑惑,为什么后者是no login shell,因为在Ubuntu中我们打开的终端程序名叫做
Terminal
在这里插入图片描述
也就是说bash也是第三方程序调用的,所以显示的是no login shell

为了进一步验证,你可以在你的Linux系统上按Ctrl + Alt + F3进入终端界面后依然发现是login shell
在这里插入图片描述
最重要的是两种shell在启动和退出时候加载的文件执行命令不一样,所以环境变量就有所区别
在这里插入图片描述
对于我的系统当为login shell时候,首先加载
在这里插入图片描述
在这里插入图片描述
退出时加载
在这里插入图片描述
当为no login shell时候,加载
在这里插入图片描述

最后的话

如有错误的地方,还望各位大佬指教,如果帮到你可以点个赞!感谢!

发布了212 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43833642/article/details/104279879