2015年2月23日 星期一

profile與bashrc的差別與在archlinux中的執行順序

根據Bash Guide for Begineers的說法,
profile用來放環境變數(Environment variables)例如: PATH, USER, MAIL,HOSTNAME及HISTSIZE等
bashrc則是用來放function與alias,
由於使用者在每次登入時都會去讀/etc/profile,
因此在多shell環境的系統上將專屬於某特定shell的設定分開放可以避免一些相容性問題.
例如Bourne shell看不懂Bash語法之類的.

直接觀察新安裝的archlinux, 跟shell有關係的初始檔有這些
/etc/profile
/etc/bash.bashrc或/etc/bashrc                  #archlinux/ubuntu/debian裡的是bash.bashrc, Fedora/CentOS裡的會是bashrc
~/.bash_profile
~/.bashrc
大致上分為profile與bashrc兩群,
實驗常見的使用情景一, 不考慮初始檔內部source別人的話,
從login到拿到shell為止, 系統會自動以這樣的順序執行這些rc檔,
1. /etc/profile
2.~/.bash_profile
這種場景不會去執行到/etc/bash.bashrc與~/.bashrc

場景二:
不login拿到shell, 例如直接/bin/bash, su 或是在X裡開個新terminal拿到shell,
執行的順序是:
1./etc/bash.bashrc
2.~/.bashrc
這個場景不會執行/etc/profile與~/.bash_profile,
但是fork出來的child shell還是會拿到parent shell的變數,
因此不做login-specific initializations沒問題

所以可以理解在多shell的系統環境下, 每個user可能使用不同的shell,
因此用profile處理login-specific initializations,
用bashrc處理Bash的shell-specific initializations, 兩者獨立.
至於從login拿到shell的人就分別在system-wide與individual-wide的profile檔裡source bashrc檔做shell-specific initializations.
果然在/etc/profile與~/.bash_profile裡看到利用source的方式叫用bashrc

/etc/profile:
if test "$PS1" && test "$BASH" && test -r /etc/bash.bashrc; then
. /etc/bash.bashrc
fi

~/.bash_profile
[[ -f ~/.bashrc ]] && . ~/.bashrc

這樣流程就很好理解了,
System-wide configuration then individual-wide configuration,
Login-specific initializations then Shell-specific initializations,
從Login開始的話就是(/etc/profile -> /etc/bash.bashrc) =>(~/.bash_profile -> ~/.bashrc)

#值得一提的是,
distributer建議自訂系統層級的環境變數做法是寫成shell script後放進/etc/profile.d,
而不是自己去改/etc/profile, 免得未來系統升級時要手動merge兩個版本的/etc/profile,
這是不太允許重灌的系統管理員會有的顧慮,
個人使用者要不要這樣做隨自己的便,
當然個人化的環境變數設定放進~/.bash_profile這是沒有太大問題的

沒有留言:

張貼留言