Bash Startup Files: .bashrc, .bash_profile, and Profile

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 146 of 205

Every time Bash starts, it may read one or more startup files before it shows the first prompt or runs the first command. These files are ordinary Bash scripts that set variables, extend PATH, define aliases and functions, and configure the prompt. They are the reason your settings are there every time you open a terminal.

The difficulty is that Bash does not always read the same files. Which files it reads depends on two questions: is the shell a login shell, and is it interactive? A setting placed in the wrong file seems to work in one terminal and is missing in another, in a cron job, or in an SSH session. This lesson explains the rules, shows them in action with marker files, and builds a clean .bash_profile and .bashrc pair.

The Files Involved

FileScopeRead by
/etc/profileall userslogin shells
~/.bash_profileone userlogin shells (first choice)
~/.bash_loginone userlogin shells (second choice)
~/.profileone userlogin shells (third choice); also used by sh-compatible shells
~/.bashrcone userinteractive shells that are not login shells
/etc/bash.bashrcall usersinteractive non-login shells on Debian and Ubuntu (a distribution addition)
~/.bash_logoutone userlogin shells when they end
the file named in $BASH_ENVanynon-interactive shells, such as scripts

Files under /etc belong to the system administrator and apply to everyone. Files in your home folder (~) are yours. Names starting with a dot are hidden, so ls -a is needed to see them.

Login Shells and Interactive Shells

A login shell is the first shell of a session: the shell started when you log in on a text console, connect with ssh, run su - username, or start Bash with bash -l (or bash --login). It is responsible for setting up the session's environment once.

An interactive shell reads commands that a person types and shows a prompt. A terminal window is interactive; a script is not. Lesson 147 explains the exact rules.

The two properties are independent, which gives the common combinations:

SituationLogin?Interactive?
SSH login, text console login, su -yesyes
New tab in most Linux terminal emulatorsnoyes
Typing bash at a promptnoyes
Running a script, bash -c '...', cron jobsnono
bash -l -c '...'yesno

Most Linux terminal emulators start a non-login interactive shell by default, because the graphical login already set up the session. The macOS Terminal application traditionally starts a login shell for every new window.

Inside Bash, shopt login_shell shows whether the current shell is a login shell, and $- contains the letter i in an interactive shell.

Which Files Bash Reads

The rules from the Bash manual are short:

  1. Login shell (interactive or not): read /etc/profile, then the first of ~/.bash_profile, ~/.bash_login and ~/.profile that exists and is readable. Only one of the three personal files is read.
  2. Interactive non-login shell: read ~/.bashrc (and, on Debian and Ubuntu, /etc/bash.bashrc first).
  3. Non-interactive shell (a script or bash -c): read no startup file, except the file named in the BASH_ENV variable, if it is set.
  4. Login shell exiting: read ~/.bash_logout.

The most important consequence: a login shell does not read ~/.bashrc by itself. This is why nearly every ~/.bash_profile or ~/.profile contains a line that loads ~/.bashrc.

Seeing the Rules in Action

To watch Bash at work, each personal startup file in a test home folder (/home/ana) was given a single line that announces it:

cd /home/ana
for f in .bash_profile .bash_login .profile .bashrc .bash_logout; do
  printf 'echo "reading ~/%s"\n' "$f" > "$f"
done

Now different kinds of shells were started with HOME=/home/ana:

bash -l -c 'echo command runs'      # login, non-interactive
bash -c 'echo command runs'         # non-login, non-interactive
echo 'echo script runs' > s.sh
bash s.sh                           # a script
BASH_ENV=~/.bashrc bash s.sh        # a script with BASH_ENV set
reading ~/.bash_profile
command runs
command runs
script runs
reading ~/.bashrc
script runs

The login shell read ~/.bash_profile, and not ~/.bash_login or ~/.profile, even though all three existed. The plain bash -c and the script read nothing at all. With BASH_ENV set, the script read the file it named.

Interactive shells were tested in a terminal (a pseudo-terminal). The default prompt of the test system was replaced with $ for readability:

reading ~/.bashrc
root@vm:~# PS1="$ "
$ echo hi
hi
$ exit
exit

A plain interactive bash read ~/.bashrc. The same test with bash -l:

reading ~/.bash_profile
root@vm:~# PS1="$ "
$ shopt login_shell
login_shell     on
$ exit
logout
reading ~/.bash_logout

The interactive login shell read ~/.bash_profile but not ~/.bashrc. When it ended, Bash printed logout instead of exit and read ~/.bash_logout. Pressing Ctrl+D instead of typing exit gave the same result.

A non-interactive login shell reads ~/.bash_logout only when it runs the exit command:

bash -l -c 'echo cmd; exit'
reading ~/.bash_profile
cmd
reading ~/.bash_logout

The Search Order for Login Files

Renaming the files one by one shows the order in which a login shell looks for them:

== all three exist
reading ~/.bash_profile
cmd
== without .bash_profile
reading ~/.bash_login
cmd
== without .bash_profile and .bash_login
reading ~/.profile
cmd

This order explains a common surprise. Ubuntu creates ~/.profile and ~/.bashrc for new users, but no ~/.bash_profile. If you create a ~/.bash_profile later, for example by following an installation guide, Bash stops reading ~/.profile in login shells, and everything that was set there disappears. A new ~/.bash_profile should therefore either contain all login settings or load ~/.profile itself with source ~/.profile.

What the System Files Do

The strace tool can list the files a program opens. Tracing Bash on Ubuntu showed which system files took part:

ShellSystem and startup files opened
bash (interactive)/etc/bash.bashrc, ~/.bashrc
bash -l (interactive)/etc/profile, /etc/bash.bashrc, ~/.bash_profile, later ~/.bash_logout
bash -l -c 'true'/etc/profile, ~/.bash_profile

In the interactive login shell, /etc/bash.bashrc was not opened by Bash itself but by Ubuntu's /etc/profile, which loads it when the shell is interactive. /etc/profile also runs every *.sh file in /etc/profile.d/, which is where installed software adds its own settings.

Options That Change the Startup Files

OptionEffect
-l, --loginact as a login shell
--noprofilelogin shell without /etc/profile and the personal login files
--norcinteractive shell without ~/.bashrc
--rcfile FILEinteractive shell that reads FILE instead of ~/.bashrc
-iforce an interactive shell

Long options such as --noprofile must come before single-letter options. bash -l --noprofile fails with bash: --: invalid option; bash --noprofile -l works.

--norc is useful for checking whether a problem comes from your settings: if it disappears in bash --norc, the cause is in a startup file. On Ubuntu, --norc also skipped /etc/bash.bashrc, so the prompt fell back to Bash's built-in default:

bash-5.2# PS1="$ "
$ exit
exit

With --rcfile /home/ana/my.rc, the trace showed /etc/bash.bashrc followed by my.rc: on Ubuntu, the system file was still read, and only ~/.bashrc was replaced.

When Bash Runs as sh

When Bash is started under the name sh (on some systems /bin/sh is Bash), it imitates the original Bourne shell. A login shell then reads only /etc/profile and ~/.profile:

(exec -a sh bash -l -c 'echo cmd')   # start Bash under the name sh
dash -l -c 'echo cmd'                 # Dash, Ubuntu's /bin/sh
reading ~/.profile
cmd
reading ~/.profile
cmd

This is why ~/.profile should contain only portable sh syntax: other shells read it too. Bash-only syntax such as [[ ]], arrays or shopt belongs in ~/.bash_profile or ~/.bashrc. The --posix option makes Bash follow the POSIX rules, in which the login shell read no personal file at all in the test, and an interactive shell reads only the file named in ENV.

What Belongs in Each File

The key to a working setup is the difference between what is inherited and what is not:

  • Exported environment variables (PATH, EDITOR, LANG) are passed from a process to every program it starts. Setting them once, in the login shell, is enough: every terminal tab, script and program started in that session inherits them.
  • Aliases, functions, shell options and the prompt are never passed to child processes (functions only with export -f). Every interactive shell must create them again, so they belong in a file every interactive shell reads.

This gives the standard division:

FilePut here
~/.bash_profile (or ~/.profile)exported variables, PATH changes, programs that should run once per login; then a line that loads ~/.bashrc
~/.bashrcaliases, functions, prompt, history settings, shopt options, completion
~/.bash_logoutclean-up at logout, such as clearing the screen

Why .bashrc Needs an Interactive Guard

The default Ubuntu ~/.bashrc starts with these lines:

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

$- holds the shell's option letters, and i means interactive. In any other shell, return stops reading the file immediately. The guard matters because ~/.bashrc can be read by shells that are not interactive: through BASH_ENV and, as the Bash manual describes, when Bash detects that it was started by a remote-shell daemon such as sshd to run a single command (ssh host command). Output printed by such a file, or slow commands in it, would then end up in the middle of a file transfer or an automated command. The guard keeps interactive-only settings where they belong.

The PATH Duplication Problem

Adding to PATH in ~/.bashrc is a frequent mistake, because ~/.bashrc runs in every interactive shell, including shells started from other shells, which already inherited the extended PATH. Appending this line to the test ~/.bashrc:

PATH="$HOME/bin:$PATH"

and counting how often ~/bin appears in PATH in a login shell and in two nested shells:

$ tr : '\n' <<< "$PATH" | grep -c ana2/bin
2
$ bash
root@vm:~# tr : '\n' <<< "$PATH" | grep -c ana2/bin
3
root@vm:~# bash
root@vm:~# tr : '\n' <<< "$PATH" | grep -c ana2/bin
4

The entry was already there twice in the login shell (once from ~/.bash_profile, once from ~/.bashrc) and grew with every nested shell. tr : '\n' puts each PATH entry on its own line, and grep -c counts the matches. The complete example avoids the problem by changing PATH only in the login file and only when the folder is not already present.

Reloading After a Change

Startup files are read only when a shell starts. After editing ~/.bashrc, either open a new terminal or load the file into the current shell with source (lesson 95):

$ type -t gl || echo none
none
$ echo "alias gl='git log --oneline'" >> ~/.bashrc
$ type -t gl || echo none
none
$ source ~/.bashrc
$ type -t gl
alias

Appending the alias to the file did not change the running shell; source did. Before reloading a file you edited heavily, bash -n ~/.bashrc checks it for syntax errors without running it (lesson 126). A broken ~/.bashrc does not prevent login, but every new shell prints the error and misses all the settings after it.

A Complete Example: A Clean .bash_profile and .bashrc Pair

The following two files form a setup that behaves the same in login shells, new terminal tabs, nested shells and scripts. They were tested in the home folder /home/ana2, which contains the folders bin and .local/bin.

~/.bash_profile:

# ~/.bash_profile: read by login shells (console, SSH, terminal set to login)
# Environment settings go here: exported variables reach every program
# started from this session, including scripts and non-login shells.

# path_prepend DIR: put DIR at the front of PATH once, if it exists
path_prepend() {
  [[ -d $1 ]] || return 0
  case ":$PATH:" in
    *":$1:"*) ;;                # already present: do nothing
    *) PATH="$1:$PATH" ;;
  esac
}
path_prepend "$HOME/.local/bin"
path_prepend "$HOME/bin"
unset -f path_prepend
export PATH

export EDITOR=nano
export LESS='-R -i'

# Interactive settings live in ~/.bashrc; load them here too, because
# Bash does not read ~/.bashrc by itself in a login shell.
if [[ -f ~/.bashrc ]]; then
  source ~/.bashrc
fi

~/.bashrc:

# ~/.bashrc: read by interactive non-login shells, and by ~/.bash_profile
# Interactive settings go here: aliases, functions, prompt, history, shopt.

# Stop here when the shell is not interactive (scripts, bash -c, scp).
case $- in
  *i*) ;;
  *) return ;;
esac

HISTSIZE=5000
HISTFILESIZE=10000
HISTCONTROL=ignoreboth          # skip duplicates and lines starting with a space
shopt -s histappend checkwinsize

alias ll='ls -alF'
alias gs='git status'
mkcd() { mkdir -p -- "$1" && cd -- "$1"; }

# Optional pieces, loaded only if present
[[ -f ~/prompt.bash ]] && source ~/prompt.bash
[[ -f ~/.bashrc.local ]] && source ~/.bashrc.local

How It Works

  • path_prepend wraps PATH in colons (":$PATH:") so that a case pattern can look for :DIR: as a whole entry; without the extra colons, the first and last entries could not be matched. A folder that does not exist is skipped, so the file also works on machines without ~/bin. The function is removed with unset -f after use, because it is only needed during startup.
  • export PATH, EDITOR and LESS are set in the login file, once per session. Every program started later inherits them.
  • The source ~/.bashrc line gives login shells the interactive settings as well. Without it, an SSH session would have the environment but no aliases or prompt.
  • The guard at the top of ~/.bashrc makes the file do nothing in non-interactive shells.
  • History settings: HISTSIZE is the number of commands kept in memory, HISTFILESIZE the number kept in ~/.bash_history, and HISTCONTROL=ignoreboth skips repeated commands and commands typed with a leading space. shopt -s histappend appends to the history file instead of overwriting it, so several open terminals do not erase each other's history; checkwinsize keeps LINES and COLUMNS up to date (lesson 149 covers shopt).
  • Optional files keep the main file short: the prompt from lesson 145 lives in ~/prompt.bash, and settings that apply to only one machine go into ~/.bashrc.local, so the main files can be shared between computers.

Running the Complete Example

Both files passed a syntax check:

bash -n ~/.bash_profile && bash -n ~/.bashrc && echo syntax ok
syntax ok

An interactive login shell, a child bash -c, a nested interactive shell and a nested login shell were then started in a terminal. The test system's /etc/profile.d adds many folders to PATH, so only the entries from /home/ana2 are shown:

root@vm:~# PS1="\$ "
$ tr : '\n' <<< "$PATH" | grep ana2
/home/ana2/bin
/home/ana2/.local/bin
$ echo "$EDITOR | $LESS"
nano | -R -i
$ type -t ll mkcd
alias
function
$ bash -c 'echo "child: $EDITOR"; type -t ll || echo "no ll"'
child: nano
no ll
$ bash
root@vm:~# PS1="(nested) \$ "
(nested) $ tr : '\n' <<< "$PATH" | grep ana2
/home/ana2/bin
/home/ana2/.local/bin
(nested) $ type -t ll
alias
(nested) $ bash -l
root@vm:~# PS1="(nested login) \$ "
(nested login) $ tr : '\n' <<< "$PATH" | grep ana2
/home/ana2/bin
/home/ana2/.local/bin
(nested login) $ exit
logout
(nested) $ exit
exit
$ exit
logout

Each check matches the design:

  • the login shell had both personal folders in PATH, the exported variables, the alias and the function;
  • the non-interactive bash -c child inherited EDITOR but had no ll alias, because aliases are not inherited and the guard stopped ~/.bashrc;
  • the nested interactive shell had the alias again, because it read ~/.bashrc itself;
  • the nested login shell ran ~/.bash_profile a second time, and path_prepend did not add the folders again.

A script started from this session behaves like the bash -c child:

# ~/s.sh
echo "script: EDITOR=$EDITOR"; type -t ll || echo "script: no ll"
script: EDITOR=nano
script: no ll

Scripts receive the environment, but not your interactive conveniences. A script that depends on an alias or a function defined in ~/.bashrc works in your terminal only by accident; it should define what it needs itself or load a library with source (lesson 95).

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Bash Startup Files: .bashrc, .bash_profile, and Profile and get answers drawn from it.

Signed-in readers only.