0
0
Linux CLIscripting~5 mins

.bashrc and .bash_profile in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you open a terminal on Linux, some files run commands automatically to set up your environment. Two important files for this are .bashrc and .bash_profile. They help customize your terminal experience by running scripts when you start a shell session.
When you want to add custom commands or shortcuts that run every time you open a new terminal window.
When you want to set environment variables like PATH only once when you log in.
When you want to run commands for interactive shells but not for login shells.
When you want to make sure your terminal looks and behaves the same every time you start it.
When you want to fix issues where some commands work in one terminal but not another.
Commands
This command shows the content of your .bash_profile file to see what commands run when you log in.
Terminal
cat ~/.bash_profile
Expected OutputExpected
export PATH="$HOME/bin:$PATH" if [ -f ~/.bashrc ]; then . ~/.bashrc fi
This command shows the content of your .bashrc file to see what commands run for each new interactive shell.
Terminal
cat ~/.bashrc
Expected OutputExpected
alias ll='ls -la' export PS1='\u@\h:\w$ ' # User specific aliases and functions
This command starts a new login shell, which reads .bash_profile to set up the environment.
Terminal
bash --login
Expected OutputExpected
No output (command runs silently)
This command starts a new interactive non-login shell, which reads .bashrc to set up the environment.
Terminal
bash
Expected OutputExpected
No output (command runs silently)
Key Concept

If you remember nothing else, remember: .bash_profile runs once at login, and .bashrc runs every time you open a new terminal window.

Common Mistakes
Adding environment variables only to .bashrc and expecting them to be set at login.
Because .bashrc is not read by login shells, so variables set there may not be available in all sessions.
Put environment variables in .bash_profile or source .bashrc from .bash_profile to share settings.
Editing .bash_profile but forgetting to source .bashrc inside it.
This causes .bashrc settings like aliases to not load in login shells.
Add 'if [ -f ~/.bashrc ]; then . ~/.bashrc; fi' inside .bash_profile.
Expecting .bashrc to run for graphical terminal sessions without login.
Some terminal emulators start login shells, others do not, causing inconsistent behavior.
Understand your terminal emulator's shell type and configure accordingly.
Summary
Use .bash_profile to set environment variables and commands that run once at login.
Use .bashrc to set aliases and commands that run for every new interactive shell.
Source .bashrc from .bash_profile to keep settings consistent across shell types.