Linux中.bashrc和.bash_profile区别


缘由:

早期学习Linux的时候就对这个问题感兴趣:~/.bashrc和~/.bash_profile以及/etc/profile等文件的作用分别是什么,启动顺序又是怎么样的呢?当时也查了很多资料,但限于当时的知识水平和经验,很多东西都不太懂,只是略微记得而已,今天中午整理了一下自己常用的~/.bashrc配置,又想起了这个问题,觉得有必要把这个问题弄清楚,于是有了下文。

搜索关键字:
  • Linux .bashrc .bash_profile
  • Linux .bashrc .bash_profile sequence
  • Linux 启动 .bashrc bash_profile
参考链接:
参考解答:
交互式登录shell

文件读取顺序:

  1. /etc/profile
  2. ~/.bash_profile, ~/.bash_login or ~/.profile: first existing readable file is read
  3. ~/.bash_logout upon logout

首先读取 /etc/profile,这是对所有用户都有效的配置;然后依次寻找下面三个文件(~/.bash_profile、~/.bash_login、~/.profile),这是针对当前登录用户的配置;但需要注意的是,这三个文件只要有一个存在,就不再读取后面的文件了。比如,要是 ~/.bash_profile 存在,就不会再读取后面两个文件了。而 ~/.bash_logout 是在用户登出系统的时候系统会读取的文件。

交互式非登录shell

A non-login shell means that you did not have to authenticate to the system. For instance, when you open a terminal using an icon, or a menu item, that is a non-login shell.

Files read:

  1. ~/.bashrc

(~/.bashrc 这个文件通常是由 ~/.bash_profile 引用的)This file is usually referred to in ~/.bash_profile:

if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
非交互式

All scripts use non-interactive shells. They are programmed to do certain tasks and cannot be instructed to do other jobs than those for which they are programmed.

Files read:

  1. defined by BASH_ENV

PATH is not used to search for this file, so if you want to use it, best refer to it by giving the full path and file name.

到这儿,困扰我多时的问题就基本解决了,心里痛快了不少。(在碰到类似问题的时候,应该首先想到的就是查阅官方文档,比如:TLDP和GNU,只要认真查看,肯定能找到准确的答案的)

==

更多参考链接:

=EOF=

,

《 “Linux中.bashrc和.bash_profile区别” 》 有 3 条评论

  1. 以「登录/交互方式」打开的bash都会在启动bash之前加载一些文件:

    首先,bash去检查/etc/profile文件是否存在,如果存在就读取并执行这个文件中的命令。

    之后,bash再按照以下列出的文件顺序依次查看是否存在这些文件,如果任何一个文件存在,就读取、执行文件中的命令:
    ~/.bash_profile
    ~/.bash_login
    ~/.profile

    这里要注意的是,这里只会检查到第一个文件就处理,即使同时存在2个或3个文件,本步骤也只会处理最优先的那个文件,而忽略其他文件。以上两个步骤的检查都可以用`–noprofile`参数进行关闭。

    当bash是以login方式登录的时候,在bash退出时(exit),会额外读取并执行~/.bash_logout文件中的命令。

    当bash是以交互方式登录时(-i参数),bash会读取并执行~/.bashrc中的命令。`–norc`参数可以关闭这个功能,另外还可以通过`–rcfile`参数指定一个文件替代默认的~/.bashrc文件。

  2. 如何在 Linux 上让一段时间不活动的用户自动登出 | Linux 中国
    https://mp.weixin.qq.com/s/EeXZu2DGADg1HnTpfmWH4g
    https://www.ostechnix.com/auto-logout-inactive-users-period-time-linux/
    `
    ◈ 方法 1:
    # 编辑 ~/.bashrc 或 ~/.bash_profile ,增加一行:
    TMOUT=100

    ◈ 方法 2:
    以 root 用户登录,创建一个内容如下的文件:
    # vi /etc/profile.d/autologout.sh
    TMOUT=100
    readonly TMOUT
    export TMOUT
    # chmod +x /etc/profile.d/autologout.sh

    ◈ 方法 3 (只适用于 SSH 会话):
    $ sudo vi /etc/ssh/sshd_config
    ClientAliveInterval 100
    ClientAliveCountMax 0

    $ sudo systemctl restart sshd
    `

回复 a-z 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注