bash enviroment - ghdrako/doc_snipets GitHub Wiki

Interactive Shells and Non-Interactive Shells

Bash provides the option of two modes in an interactive shell, i.e., login and non-login. When we log in to a system using ssh, we get an interactive login shell. This shell reads startup files when invoked.

However, when we invoke a new shell on an already logged-in shell, we get an interactive, non-login shell. This type of shell executes only the .bashrc file.

When a shell doesn’t need any human intervention to execute commands, we call it a non-interactive shell. For example, when a script forks a child shell for the execution of commands, the child shell is a non-interactive shell. This shell doesn’t execute any startup file. It inherits environment variables from the shell that created it.

Bash Startup Files

Startup files contain commands that are to be executed on shell startup. This happens even before displaying the command prompt.

.bash_profile

The .bash_profile file contains commands for setting environment variables. Consequently, future shells inherit these variables.

In an interactive login shell, Bash first looks for the /etc/profile file. If found, Bash reads and executes it in the current shell. As a result, /etc/profile sets up the environment configuration for all users.

Similarly, Bash then checks if .bash_profile exists in the home directory. If it does, then Bash executes .bash_profile in the current shell. Bash then stops looking for other files such as .bash_login and .profile.

If Bash doesn’t find .bash_profile, then it looks for .bash_login and .profile, in that order, and executes the first readable file only.

.bashrc

bashrc contains commands that are specific to the Bash shells. Every interactive non-login shell reads .bashrc first. Normally .bashrc is the best place to add aliases and Bash related functions.

.profile

During an interactive shell login, if .bash_profile is not present in the home directory, Bash looks for .bash_login. If found, Bash executes it. If .bash_login is not present in the home directory, Bash looks for .profile and executes it.

.profile can hold the same configurations as .bash_profile or .bash_login. It controls prompt appearance, keyboard sound, shells to open, and individual profile settings that override the variables set in the /etc/profile file.

Generally, environment variables are put into .bash_profile. Since the interactive login shell is the first shell, all the default settings required for the environment setup are put in .bash_profile

Aliases and functions are put into .bashrc to ensure that these are loaded every time a shell is launched from within the existing environment.

To avoid login and non-login interactive shell setup difference, .bash_profile calls .bashrc.

.bash_profile:
if [ -f ~/.bashrc ];
then 
    .  ~/.bashrc; 
fi 
PATH=$PATH:$HOME/bin export PATH