3

What is the point of having both .bash_profile and .bashrc, with the former typically sourcing the latter, which in turn sources /etc/bashrc upon login? What would be the downside of putting all that is in .bashrc in .bash_profile (or vice versa) and source only that one login script?

amphibient
  • 12,472
  • 18
  • 64
  • 88

1 Answers1

11

Only .bashrc is run on non-login shells, while only .bash_profile is run on login shells.

.bashrc should typically contain things you want to set in every shell you open, like aliases, functions, etc. These are per shell session items that are not inherited from environment.

.bash_profile should contain things that need to be defined at login time only, like PATH and other environment variables, startup programs, etc. You just need things once, not in every shell you open. In most cases, you also need the things from .bashrc in your login shell. That's why .bash_profile sources .bashrc as well, but .bashrc doesn't usually source .bash_profile.

/etc/bashrc and /etc/profile are system wide settings made by the sys admin or the package manager. /etc/profile is sourced automatically in each login shell, before ~/.bash_profile. /etc/bashrc is not sourced, so it needs to be sourced from ~/.bashrc when required.

Now, you can club the two into a single file and link the other file to the first one. But you have to make sure that PATH and other variables are not relative defined (like PATH=$HOME/bin:$PATH) otherwise they will just keep becoming needlessly bigger. Also, you have to be careful of starting programs repeatedly. It's just easier to have these two separate.

Relevant section from the bash man page:

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 --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.

Munir
  • 3,332
  • So it sounds like HISTTIMEFORMAT should probably be defined in .bashrc, so it applies to all shells opened? – Wildcard Jan 25 '18 at 22:33