
在使用Linux的时候,我们经常设置环境变量,.bash_profile和.bashrc文件都可以用来设置,那么两者到底有什么区别
1. Interactive Login和Non-Login Shell
- Interactive Shell: a shell that reads and writes to a user’s terminal
- Non-interactive Shell: a shell that is not associated with a terminal, like when executing a script.
1.1 Interactive Shell
An interactive shell can be either login or non-login shell.
- login shell: A login shell is invoked when a user login to the terminal either remotely via ssh or locally, or when Bash is launched with the
--loginoption - non-login shell: An interactive non-login shell is invoked from the login shell, such as when typing
bashin the shell prompt or when opening a new Gnome terminal tab.
1.2 Bash Startup Files
When invoked as an interactive login shell, Bash looks for the
/etc/profilefile, and if the file exists , it runs the commands listed in the file. Then Bash searches for~/.bash_profile,~/.bash_login, and~/.profilefiles, in the listed order, and executes commands from the first readable file found.
When Bash is invoked as an interactive non-login shell, it reads and executes commands from
~/.bashrc, if that file exists, and it is readable.
1.3 做个实验
给Shell1中设置一个alias
1 | [toni@os ~/workpalce/pay_otel]$ echo "alias gitst='git status'" >> ~/.bashrc |
设置完后立刻打开一个新的Shell,可以看到设置的alias是立刻剩下的,说明.bashrc是interactive non-login shell会读取的
1 | [toni@os ~/workpalce/pay_otel]$ gitst |
2. .bashrc与.bash_profile的区别
.bash_profileis read and executed when Bash is invoked as an interactive login shell, while.bashrcis executed for an interactive non-login shell- Use
.bash_profileto run commands that should run only once, such as customizing the$PATHenvironment variable . - Put the commands that should run every time you launch a new shell in the
.bashrcfile. This include your aliases and functions , custom prompts, history customizations , and so on. - Typically,
~/.bash_profilecontains lines like below that source the.bashrcfile. This means each time you log in to the terminal, both files are read and executed.
1 | if [ -f ~/.bashrc ]; then |
Most Linux distributions are using
~/.profileinstead of~/.bash_profile. The~/.profilefile is read by all shells, while~/.bash_profileonly by Bash.