login shell 、交互式 shell 辨别方法

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

什么是login shell ?

  • 用户登录到 linux 后的第一个shell 终端就是 login shell,后续在这个 shell 终端中再使用 sh 命令启动的 shell 就不是 login shell 了。

如何鉴别当前 shell 是不是 login shell ?

  • login shell 的第0个参数以-开头
[root@VM-218-159-centos ~]# echo $0
-bash 

An interactive shell is one started without non-option arguments and without the -c option whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state.

什么是交互式 shell ?

  • 通俗点讲,就是每次只执行一行代码即返回结果的 shell

如何鉴别当前 shell 是不是交互式shell ?

  • 在交互式 shell 下 PS1 不为空,$- 包括 i ,反之则是非交互式shell。
[root@VM-218-159-centos ~]# echo $PS1
[\u@\h \W]\$
[root@VM-218-159-centos ~]# echo $-
himBHs

The following paragraphs describe how bash executes its startup files. If any of the files exist but cannot be read, bash reports an error. Tildes are expanded in file names as described below under Tilde Expansion in the EXPANSION section.

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 behav­ior.
When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists.

login shell 启动时运行 setup file 的顺序?

  • /etc/profile --> ~/.bash_profile-->~/.bash_login-->~/.profile

login shell 退出时执行的文件?

  • ~/.bash_logout

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 的交互式 shell 启动时执行的 setup file ?

  • ~/.bashrc

When bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed:
if [ -n "$BASH_ENV" ]; then
. "$BASH_ENV";
fi
but the value of the PATH variable is not used to search for the file name.

非交互式 shell 启动时怎么 setup ?

  • 并没有确切的初始化文件可以执行,而是将 BASH_ENV 的值当作初始化文件的文件名。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容