.bashrc Isn't Working
Login and Non-Login shells are common in Unix based systems and each source different files. Learn a trick to ensure configurations in non-login shells are applied to login shells with .bashrc and .bash_profile.
Table of Contents 📖
.bashrc
.bashrc is typically used to define interactive shell settings like aliases, functions, and prompt customization.
# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
However, if .bashrc isn't sourced in a login shell, these settings won't be available.
Login and Non-Login Shells
In Unix based systems, there are two types of shell sessions: login and non-login. Login shell sessions start when a user logs into the system (think SSH). Non-Login shell sessions are started after the login process has already been completed (think running a script from within an already logged-in session). Both of these shell sessions source different configurations:
- Login - /etc/profile, ~/.bash_profile, ~/.bash_login, or ~/.profile (depending on the shell and configuration).
- Non-Login - /etc/bash.bashrc (for bash, globally) and ~/.bashrc (for bash, per user).
Handling Both
As both shell types source different files, certain features and functions might not be available in different shells. However, in most login shell configuration files, .bashrc will also run in interactive login shells because of this line of script code.
# if running bash
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi
This code checks if the current shell is bash, and if .bashrc exists, it sources .bashrc. The purpose of this is to ensure that the configurations in ~/.bashrc are applied even when Bash is invoked as a login shell. When Bash is started as a login shell, it does not automatically load ~/.bashrc. Instead, it looks for ~/.bash_profile, ~/.bash_login, or ~/.profile. This is a fallback mechanism to maintain consistency across login and non-login shells for Bash users.