How-to: Bash startup files

~/.bashrc

From the bash man page:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option can be used when the shell is started to inhibit this behavior.

When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This can be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc

Every new terminal window/tab that you open will load .bashrc

On a brand new user account, none of these files will exist, they can be created with any suitable text editor that is capable of creating plain text files with Unix style (LF) line endings. Save them into your home folder (~/)

Commands you will typically want to include in .bashrc include: history variables to increase the history available, setting a Prompt with the PS1 variable and bind keymappings.

Sourcing files

If you have a lot of shell configurations, you may want to split them out into several subfiles and use the source builtin to load them from .bashrc:
source ~/.bash-options
source ~/.bash-aliases
source ~/.bash-functions

Alternatively, to ensure the files actually exist before loading

if [ -f ~/.bash-aliases ]; then
. ~/.bash-aliases
fi

The command . ~/.bash-aliases will source ~/.bash-aliases in the context of the currently running shell.

This is particularly useful for adding aliases, the separate file makes it easier to re-load them when you make changes.

Related Linux commands

bash prompt - PS1
bashrc_dispatch - use symlinks to reorganise .bashrc, .bash_profile and .profile.
.inputrc - Startup files (Set Key bindings and Tab completion).
bashrc example - Tom Ryder.
flowblok’s blog - Which startup files run for bash and zsh.
alias - Create an alias.


 
Copyright © 1999-2024 SS64.com
Some rights reserved