.bash_profile VS .bashrc

本文详细解释了在Linux、Unix及MacOSX环境下,.bash_profile与.bashrc配置文件的作用与区别。.bash_profile用于登录shell的初始化配置,而.bashrc则针对每次新开启的交互式shell。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介:

以前常用Linux,最近在Mac的terminal上配置git命令自动补全,发现将配置写入~/.bashrc中不起作用,网上查到别人是将配置写入~/.bash_profile.其实自己以前一直也没有好好弄明白这两个文件的区别。今天查了一下,整理在笔记中:

在Linux,Unix, 和Mac OS X中,都可以通过在home目录中的 .bashrc和 .bash_profile来配置bash. 如果home目录中没有,这两个文件都是可以手动创建的。但是为什么会有两个不同的配置文件呢?他们之间的有什么区别?


详解:

在terminal里运行一下$man bash, 通过关键字查找,可以看到一些提示信息:

       The  following  paragraphs describe how bash executes its startup files.  If any of the files exist but cannot be read,bash reports an

       error.  Tildes are expanded in file names as described below underTildeExpansion in theEXPANSION section.


       When bash is invoked as an interactive login shell, or as a non-interactive shell with the--login option, it first reads and  executes

       commands  from  the  file/etc/profile, if that file exists.  After reading that file, it looks for~/.bash_profile,~/.bash_login, and

       ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable.  The--noprofile option  may

       be used when the shell is started to inhibit this behavior.


       When a login shell exits,bash reads and executes commands from the file~/.bash_logout, if it exists.


       When  an  interactive shell that is not a login shell is started,bash reads and executes commands from~/.bashrc, if that file exists.

       This may be inhibited by using the--norc option.  The--rcfilefile option will forcebash to read  and  execute  commands  from file

       instead of ~/.bashrc.


   ~/.bash_profile

              The personal initialization file, executed for login shells

   ~/.bashrc

              The individual per-interactive-shell startup file

可以明显的看到,.bash_profile 是登录的shell的个人配置初始化文件。.bashrc是非登录shell的交互启动文件,关键在于登录与非登录。


当我们登录(login)时,系统会要求输入用户名和密码,通过ssh命令远程登录时也是要求每次输入用户名和密码,除非配置ssh key(也是登录认证)。这时候.bash_profile会在初始化命令之前被执行,用来配置shell,可以通过users命令查看当前登录的用户。

如果已经登录到电脑中,再重新在Gnome或者KDE开一个终端窗口(比如xterm). 这时.bashrc在弹出命令提示窗口之前被执行。在终端中运行/bin/bash, 将会执行.bashrc

我在我的Mac terminal的home目录下同时创建了.bashrc 文件和 .bash_profile文件,并且在这两个文件的末尾行分别加了一句测试语句:

~/.bashrc:

echo -e "\n~/.bashrc is executed!"

~/.bash_profile:

echo -e "\n~/.bash_profile is executed!"

下面是运行结果:

重新打开一个terminal,执行.bash_profile, 在terminal中运行/bin/bash, 执行.bashrc


.bash_profile 只在登录时执行,.bashrc在每次创建新窗口时都会执行。Mac中默认是执行.bash_profile, 即登录shell。


如果让.bashrc在登录shell时也运行,这样会让两个文件中的设置同时生效,而不用配置两次,可以在~/.bash_profile中加入一下语句:   

if [ -f ~/.bashrc ]; then
    source ~/.bashrc
fi




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值