Contents

.bashrc、.bash-profile和.profile的区别

1. 概述

Bash shell 使用一些启动文件来设置环境。这些文件为 shell 本身和系统用户确定了某些 Bash shell 配置。 在本教程中,我们将了解一些启动文件,例如*.bashrc*、.bash-profile和*.profile*以及它们的区别。

2. 交互式 Shell 和非交互式 Shell

Bash 在交互式 shell 中提供了两种模式的选择,即 login 和 non-login

当我们使用*ssh *登录系统时,我们会得到一个交互式登录 shell。此 shell 在调用时读取启动文件。

但是,当我们在已经登录的 shell 上调用新的 shell 时,我们会得到一个交互式的非登录 shell。这种类型的 shell 只执行*.bashrc*文件。

当 shell 不需要任何人为干预来执行命令时,我们称其为非交互式 shell。例如,当脚本派生一个子 shell 以执行命令时,子 shell 是一个非交互式 shell。此 shell 不执行任何启动文件。它从创建它的 shell 继承环境变量。

3. Bash 启动文件

启动文件包含要在 shell 启动时执行的命令。因此,shell 会自动执行这些文件中存在的命令来设置 shell。甚至在显示命令提示符之前就会发生这种情况。

3.1. .bash_profile的意义

.bash_profile文件包含用于设置环境变量的命令。因此,未来的 shell 会继承这些变量。

在交互式登录 shell 中,Bash 首先查找*/etc/profile文件。如果找到,Bash 会在当前 shell 中读取并执行它。**结果,/etc/profile*为所有用户设置了环境配置**。

同样,Bash 然后检查主目录中是否存在*.bash_profile* 。如果是,则 Bash 执行。当前 shell 中的*.bash_profile*。然后 Bash 停止寻找其他文件,例如*.bash_login.profile*。

如果 Bash 没有找到*.bash_profile*,然后它会查找*.bash_login .profile*,按此顺序,仅执行第一个可读文件

让我们看一个样本*.bash_profile文件。在这里,我们正在设置和导出PATH*变量:

echo "Bash_profile execution starts.."  
PATH=$PATH:$HOME/bin; 
export PATH; 
echo "Bash_profile execution stops.."

我们将在交互式登录 shell 的命令提示符之前看到以下输出:

Bash_profile execution starts.. 
Bash_profile execution stops.. 
[[[email protected]](/cdn_cgi/l/email_protection) ~]$

3.2. .bashrc的意义

.bashrc包含特定于 Bash shell 的命令。*每个交互式非登录 shell 读取。首先是.bashrc一般bashrc*是添加别名和 Bash 相关函数的最佳位置。

Bash shell 在主目录中查找*.bashrc文件,并使用source 在当前 shell 中执行它。 让我们看一下示例.bashrc*文件:

echo "Bashrc execution starts.." 
alias elui='top -c -u $USER' 
alias ll='ls -lrt' 
echo "Bashrc execution stops.."

我们将在交互式非登录 shell 上的命令提示符之前看到以下输出:

[dsuser@server ~]$ bash
Bashrc execution starts.. 
Bashrc execution stops.. 
[dsuser@server ~]$

3.3. .profile的意义

在交互式 shell 登录期间,如果主目录中不存在*.bash_profile* ,Bash 会查找*.bash_login*。如果找到,Bash 会执行它。如果主目录中不存在*.bash_login*,Bash 会查找 .profile并执行它。

.profile可以包含与*.bash_profile 或 .bash_login相同的配置。*它控制提示外观、键盘声音、要打开的 shell 以及覆盖/etc/profile文件中设置的变量的单个配置文件设置。

4. 差异

在每次交互式登录时,Bash shell 都会执行*.bash_profile*。如果在主目录中找不到*.bash_profile* ,Bash 会执行从 .bash 中找到的第一个可读文件*.bash_login.profile。然而,在每次交互式非登录 shell 启动时,Bash 都会执行.bashrc*。

通常,环境变量放在*.bash_profile中。由于交互式登录 shell 是第一个 shell,因此环境设置所需的所有默认设置都放在.bash_profile*中。因此,它们只设置一次,但在所有子 shell 中继承。

同样,别名和函数被放入*.bashrc*以确保每次从现有环境中启动 shell 时都加载它们。

**但是,为避免登录和非登录交互式 shell 设置差异,.bash_profile 调用 .bashrc。*结果,我们将看到下面的代码片段被插入到.bash_profile中,因此在每个交互式登录 shell 中,.bashrc*也会在同一个 shell 中执行:

if [ -f ~/.bashrc ];
then 
    .  ~/.bashrc; 
fi 
PATH=$PATH:$HOME/bin export PATH