[吹毛求疵] 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 @   tfel-ypoc  阅读(96)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示