[吹毛求疵] Linux 启动文件 .bashrc 和 .bash_profile 的区别

Linux用户大多都知道可以通过~/.bashrc、~/.bash_profile等文件来实现命令自定义、开机自动执行等需求

今天突然灵光一闪,想探究下这几个文件的区别在哪里,于是产生了此篇记录。

 

结论

bash_profile 是 各用户独有的启动文件,当调用了 login shell 时,该文件被应用;

bashrc 同样是各用户独有,每个 交互式shell 会调用该文件


名词释义

bash_profile 无须多言

bashrc 中的 rc 理解为 “Run Commands”

官方注解

此段摘自 CentOS 7 中 bash 的 man page

FILES
       /bin/bash
              The bash executable
       /etc/profile
              The systemwide initialization file, executed for login shells
       /etc/bash.bash_logout
              The systemwide login shell cleanup file, executed when a login shell exits
       ~/.bash_profile
              The personal initialization file, executed for login shells

       ~/.bashrc
              The individual per-interactive-shell startup file

       ~/.bash_logout
              The individual login shell cleanup file, executed when a login shell exits
       ~/.inputrc
              Individual readline initialization file

概念扩展

登录shell(login shell) 和 非登录shell(non-login shell)

登录shell(login shell)

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

登录shell 的 $0 参数以 ‘-’ 开头,或者是由带 --login 参数的bash命令启动而来

[root@localhost ~]# echo $0
-bash

        Note:

#su - 用户名
#这种命令也会启动login shell

非登录shell(non-login shell)

与登录shell概念相对应的,就是non-login shell了

分辨方式

  • echo $0

    不一定有效,因为如果使用 --login 参数启动的 shell,它也是 login shell,但它的参数会显示为 'bash',不带有 '-'

  • exit

    login shell 此命令会显示 logout(中文显示“登出”)
    non-login shell 则会显示 exit

  • logout

    login shell 可以正常调用此命令
    non-login shell 则会提示如 “不是登录shell:使用`exit`” 的提示

交互式shell 与 非交互式shell

这里属于拓展阅读了,直接看下man page

       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的总结》 

分辨方式

使用

echo $-

并查看输出,输出内容带 'i' 则为交互式shell

至于其它的输出信息的含义,参考 bash 的 man page 内容的 set 部分

posted @ 2021-09-02 14:03  tfel-ypoc  阅读(91)  评论(0编辑  收藏  举报