想必大家都在linux系统中设置过环境变量,有没有感觉不知道应该在哪个文件里面设置呢?比如~/.profile, ~/.bash_profile, ~/.bashrc , /etc/profile , 等等。

其实这些文件会在不同的场景下被运行。

shell分为login shell , non-login shell , interactive shell , non-interactive shell 。

比如当你ssh example.com之后,获取的就是interactive login shell , 

当你ssh example.com "uptime" , 获取的就是non-interactive login shell ,

当你在登录的机器上su user之后,获取的就是interactive non-login shell,

当你在登录的机器上su - user之后,获取的就是interactive login shell 。

下面是在不同场景下执行文件的先后顺序,A, B, C表示先执行A,再执行B,再执行C。

B1,B2,B3表示按顺序找文件,先找到谁就只执行谁。

+----------------+-----------+-----------+------+
|                |Interactive|Interactive|Script|
|                |login      |non-login  |      |
+----------------+-----------+-----------+------+
|/etc/profile    |   A       |           |      |
+----------------+-----------+-----------+------+
|/etc/bash.bashrc|           |    A      |      |
+----------------+-----------+-----------+------+
|~/.bashrc       |           |    B      |      |
+----------------+-----------+-----------+------+
|~/.bash_profile |   B1      |           |      |
+----------------+-----------+-----------+------+
|~/.bash_login   |   B2      |           |      |
+----------------+-----------+-----------+------+
|~/.profile      |   B3      |           |      |
+----------------+-----------+-----------+------+
|BASH_ENV        |           |           |  A   |
+----------------+-----------+-----------+------+
|                |           |           |      |
+----------------+-----------+-----------+------+
|                |           |           |      |
+----------------+-----------+-----------+------+
|~/.bash_logout  |    C      |           |      |
+----------------+-----------+-----------+------+


链接

https://shreevatsa.wordpress.com/2008/03/30/zshbash-startup-files-loading-order-bashrc-zshrc-etc/