What is the purpose of .bashrc and how does it work?
.bashrcis a shell script that Bash runs whenever it is started interactively. It initializes an interactive shell session. You can put any command in that file that you could type at the command prompt.
You put commands here to set up the shell for use in your particular environment, or to customize things to your preferences. A common thing to put in
.bashrcare aliases that you want to always be available.
.bashrcruns on every interactive shell launch. If you say:
$ bash ; bash ; bash
and then hit Ctrl-D three times,
.bashrcwill run three times. But if you say this instead:
$ bash -c exit ; bash -c exit ; bash -c exit
.bashrcwon't run at all, since
-cmakes the Bash call non-interactive. The same is true when you run a shell script from a file.
.profilewhich are only run at the start of a new login shell. (
bash -l) You choose whether a command goes in
.bash_profiledepending on on whether you want it to run once or for every interactive shell start.
As a counterexample to aliases, which I prefer to put in
.bashrc, you want to do
.bash_profileinstead, since these changes are typically not idempotent:
If you put that in
.bashrcinstead, every time you launched an interactive sub-shell,
:/some/additionwould get tacked on to the end of the
PATHagain, creating extra work for the shell when you mistype a command.
You get a new interactive Bash shell whenever you shell out of
:sh, for example.
Minor quibble: unlike most other shells, bash does *not* automatically load the per-instance config file `.bashrc` when it's started as a login shell. This can sometimes lead to unexpected behavior. The usual workaround is to source `.bashrc` from `.profile` or `.bash_profile` instead.