Tuesday, August 12, 2014

Bash Startup Files Explained

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 ~/.bash_profile, ~/.bash_login, ~/.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.

su [user]
Runs interactive shell as user. Does not load variables or change directory
1- Calls ~/.bashrc

su - [user]
su -l [user]
Same as a login shell
1- Calls ~/.bash_profile
2- Calls ~/.bashrc (from .bash_profile)

sudo -i -u [user]
Runs a login shell by default
1- Calls ~/.bash_profile
2- Calls ~/.bashrc (from .bash_profile)

sudo -i -u [user] /bin/bash
Runs a login shell as specified
1- Calls ~/.bash_profile
2- Calls ~/.bashrc (from .bash_profile)
3- Calls ~/.bashrc

sudo -i -u [user] /bin/bash --norc
Runs a login shell and does not load ~/.bashrc
1- Calls ~/.bash_profile
2- Calls ~/.bashrc (from .bash_profile)

sudo -i -u [user] /bin/bash --rcfile [file]
Runs a login shell and loads specified [file] instead of ~/.bashrc
1- Calls ~/.bash_profile
2- Calls ~/.bashrc (from .bash_profile)
3- Calls [file]

No comments: