Flow of Control during Bash Startup

When I began using the Bourne-Again Shell (Bash), I used to get majorly confused about which scripts get executed automatically during Bash's startup procedure under various conditions. So I finally RTFMed and then compiled the following diagram and a short summary:

How it works

Flow of Control during Bash Startup

The red initiators and terminators denote the way how Bash is being started and terminated: as a login shell, as an interactive non-login shell, as a non-interactive non-login shell (essentially when a shell script is being run as a cron job or the like), or from within an X session. The white and gray boxes are files that get executed by Bash. The blue box symbolizes the (interactive or non-interactive) Bash session.

The dashed arrows originating from ~/.xsession denote that flow of control only proceeds from there as soon as a Bash is started from an X session. Most desktop managers are set up to start interactive non-login shells by default (`xterm`, `konsole`, `bash`), but usually login shells can be instated instead through command-line parameters (`xterm -ls`, `konsole --ls`, `bash --login`).

Of the files ~/.bash_profile, ~/.bash_login, and ~/.profile, only the first one found by Bash gets executed. That is, these three files are equivalent, and if ~/.bash_profile exists (as is assumed in the following), the others are ignored.

Concluding, the relevant files and their most appropriate uses are:

/etc/profile system-wide settings and actions (login shells only)
~/.bash_profile user-specific settings and actions (login shells only)
~/.bashrc user-specific settings and actions (all non-login shells, i.e. sub-shells and shell scripts, in particular cron scripts)
~/.xsession user-specific settings and actions (executed once on start of X session)
~/.bash_logout user-specific clean-up actions (executed on termination of login shells)

A common practice is to `source ~/.bashrc` in ~/.bash_profile, so that ~/.bashrc gets executed in login shells as well (not only in non-login shells) and redundant code in both files can be avoided.

See also…

bash(1), Xsession(5).

efpaacnoop.epjaadovbe@venus.mehnle.net