三个文件是按这个顺序读取的?
.bash_profile
.profile
.bashrc
Run Code Online (Sandbox Code Playgroud)
当我第一次打开终端时不会发生这种情况。
我在附加到文件 init.log 的文件中有跟踪语句。请看以下内容。它在打开终端后开始。我已经发表了评论以显示在 su 命令之后日志的位置。
stephen@debian:~$ cat init.log
reading .bashrc
done reading .bashrc
stephen@debian:~$ su - stephen
Password:
stephen@debian:~$ cat init.log
reading .bashrc
done reading .bashrc
#
# after su
#
reading .bash_profile
reading .profile
reading .bashrc
done reading .bashrc
done reading .profile
done reading .bash_profile
stephen@debian:~$
Run Code Online (Sandbox Code Playgroud)
因此 su - login 会触发预期的序列,但是初始登录仅读取 bashrc。这不可能是正确的。有人可以解释在什么条件下会发生这种情况。我可以修改 bashrc 和配置文件,以便初始读取包括所有预期的文件,但我宁愿找到问题的根源并在那里修复它。
答案是 bash 将查找这三个文件(在略有不同的情况下),但通常只会执行其中之一。
当运行登录shell 时(通常是当您登录终端时,或者当您打开 GNOME 终端或类似的,或者当您使用时su -
),更具体地说是一个交互式登录 shell,那么它将在系统范围内执行,然后/etc/profile
完成,它将查找~/.bash_profile
,~/.bash_login
或~/.profile
并执行它找到的第一个。
从 bash 手册页:
当 bash 作为交互式登录 shell 或作为具有
--login
选项的非交互式 shell 调用时,它首先从文件中读取并执行命令/etc/profile
(如果该文件存在)。读取该文件后,它会按该顺序查找~/.bash_profile
、~/.bash_login
、 和~/.profile
,并从第一个存在且可读的命令中读取和执行命令。--noprofile
当 shell 启动时可以使用该选项来禁止这种行为。
当 bash 作为交互式 shell 执行时,更具体地说是交互式非登录 shell,那么它将读取 ~/.bashrc
并执行该文件。
从 bash 手册页:
当一个不是登录 shell 的交互式 shell 启动时,bash 读取并执行来自 的命令
~/.bashrc
(如果该文件存在)。这可以通过使用--norc
选项来禁止。该--rcfile
文件选项将强制bash读取和文件,而不是执行命令~/.bashrc
。
Linux 发行版通常做的是装运~/.bash_profile
,~/.profile
并且~/.bashrc
该链彼此,让你有更一致的行为,而不必复制文件之间设置文件...
例如,Debian 的默认~/.profile
包含这个片段:
# if running bash
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi
Run Code Online (Sandbox Code Playgroud)
所以它是明确的 sourcing ~/.bashrc
,因此登录和非登录交互式 shell 都将包含添加到该文件的自定义。