Last Updated: February 25, 2016
·
3.773K
· victorbrca

Bash Startup Files Explained

See this post on my blog.

After spending some time troubleshooting an issue at work, I decided to put together a quick explanation of the different types of shells and what startup files each of them calls.

Shell Types

Login Shells

A login shell (also an interactive shell) is the first process that executes under your user ID when you log in for an interactive session.

Bash runs the following scripts on login:

  • /etc/profile
  • The first found of ~/.bashprofile, ~/.bashlogin, ~/.profile

Interactive Shells

An interactive shell reads commands from user input on a tty. Among other things, such a shell reads startup files on activation, displays a prompt, and enables job control by default. The user can interact with the shell.

On entering an interactive terminal, Bash also executes:

  • /etc/bash.bashrc
  • ~/.bashrc

Non-interactive shells

A shell running a script is always a non-interactive shell.

Non-interactive shells do not usually execute startup files, however different shells act differently. Bash always reads ~/.bashrc when it's invoked by rshd or sshd, even if it's not interactive (but not if it's called as sh). Zsh always reads ~/.zshenv.

Also note that aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt

shopt -s expand_aliases

Examples

All the following examples assume that ~/.bashrc is called from ~/.bash_profile. Each example also shows in what order the startup files are called.

Example 1

su [user]

Runs interactive shell as user. Does not load variables or change directory.<br>
1- Calls ~/.bashrc

Example 2

su - [user]<br>
su -l [user]

Same as a login shell<br>
1- Calls ~/.bashprofile<br>
2- Calls ~/.bashrc (from .bash
profile)

Example 3

sudo -i -u [user]

Runs a login shell by default<br>
1- Calls ~/.bashprofile<br>
2- Calls ~/.bashrc (from .bash
profile)

Example 4

sudo -i -u [user] /bin/bash

Runs a login shell as specified<br>
1- Calls ~/.bashprofile<br>
2- Calls ~/.bashrc (from .bash
profile)<br>
3- Calls ~/.bashrc

Example 5

sudo -i -u [user] /bin/bash --norc

Runs a login shell and does not load ~/.bashrc<br>
1- Calls ~/.bashprofile<br>
2- Calls ~/.bashrc (from .bash
profile)

Example 6

sudo -i -u [user] /bin/bash --rcfile [file]

Runs a login shell and loads specified [file] instead of ~/.bashrc<br>
1- Calls ~/.bashprofile<br>
2- Calls ~/.bashrc (from .bash
profile)<br>
3- Calls [file]