When you open up a terminal there are a number of commands that get run in the background before you even do anything. These commands are contained in ‘startup files’ and can often be edited in order to change the default behaviour of your terminal.
Bash is the default shell and language for most Linux terminals. It is also installed on macOS but is no longer the default.
When you open a Bash shell the following startup files might get run (depending on which mode(s) the terminal is opened in and also on if the files exist - not all of them have to) in the following order:
/etc/profile
(this calls path_helper
which initialises the PATH variable)~/.bash_profile
, ~/.bash_login
or ~/.profile
(only the first one that exists)/etc/bash.bashrc
(only for some Linux distros, and not on macOS)~/.bashrc
Additionally, two files are run at the end of a login shell’s session:
~/.bash_logout
/etc/bash_logout
Opening Terminal on Ubuntu will create a Bash shell in interactive but not in login mode. This means that /etc/bash.bashrc
and ~/.bashrc
get sourced (the code they contain gets run).
Here’s how to check which modes you are in:
Check if you are in an interactive shell:
[[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive'
Check if you are in a login shell:
shopt -q login_shell && echo 'Login shell' || echo 'Not login shell'
Z Shell (zsh) is the default shell and language for macOS terminals. By default, opening Terminal on macOS will create a shell in both interactive and login modes although sub-shells (created by, for example, running zsh
in a terminal) will only be interactive, not login.
When you open a shell the following startup files might get run (depending on which mode(s) the terminal is opened in and also on if the files exist - not all of them have to) in the following order:
/etc/zshenv
~/.zshenv
/etc/zprofile
. This calls path_helper
which reads the paths contained in the following files in order, concatenates them and prepends them to PATH (note that if the PATH variable is already set it will not add duplicate paths to it but it could have the effect of re-ordering it):
/etc/paths
/etc/paths.d
~/.zprofile
/etc/zshrc
~/.zshrc
/etc/zlogin
~/.zlogin
Additionally, two files are run at the end of a login shell’s session:
~/.zlogout
/etc/zlogout
Remember that a shell can be both interactive and login, or it could be interactive but non-login or it could be neither. It’s rare (but not impossible) to get a non-interactive login shell. Here’s how to check:
Check if you are in an interactive shell:
[[ -o interactive ]] && echo "Interactive" || echo "Non-Interactive"
Check if you are in a login shell:
[[ -o login ]] && echo "Login" || echo "Non-Login"