#Linux

.bash_profile vs .bashrc
在使用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 --login option
  • non-login shell: An interactive non-login shell is invoked from the login shell, such as when typing bash in 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/profile file, and if the file exists , it runs the commands listed in the file. Then Bash searches for ~/.bash_profile, ~/.bash_login, and ~/.profile files, 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
2
3
4
[toni@os ~/workpalce/pay_otel]$ echo "alias gitst='git status'" >> ~/.bashrc 
[toni@os ~/workpalce/pay_otel]$ gitst
Hey! No command 'gitst' found, did you mean 'dist'?
[toni@os ~/workpalce/pay_otel]$

设置完后立刻打开一个新的Shell,可以看到设置的alias是立刻剩下的,说明.bashrc是interactive non-login shell会读取的

1
2
3
4
5
6
7
8
9
10
11
[toni@os ~/workpalce/pay_otel]$ gitst
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: dtools.sh
modified: pay_otel.go

no changes added to commit (use "git add" and/or "git commit -a")

2. .bashrc与.bash_profile的区别

  • .bash_profile is read and executed when Bash is invoked as an interactive login shell, while .bashrc is executed for an interactive non-login shell
  • Use .bash_profile to run commands that should run only once, such as customizing the $PATH environment variable .
  • Put the commands that should run every time you launch a new shell in the .bashrc file. This include your aliases and functions , custom prompts, history customizations , and so on.
  • Typically, ~/.bash_profile contains lines like below that source the .bashrc file. This means each time you log in to the terminal, both files are read and executed.
1
2
3
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi

Most Linux distributions are using ~/.profile instead of ~/.bash_profile. The ~/.profile file is read by all shells, while ~/.bash_profile only by Bash.

3. 参考

  1. .bash_profile vs .bash_rc
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×