1)第一次嘗試的天真做法:
以註冊golang環境變數為例:
cd /etc/profile.dls -rtltouch custom.sh # or any file name you like to create a new filels -rtlecho "export PATH=\${PATH}:/usr/local/go/bin" > custom.sh && chmod 755 custom.shless custom.sh. custom.shecho $PATHreboot
不建議直接寫入/etc/profile,而是在/etc/profile.d檔案夾下建立一個自己寫的shell指令碼,內容是:
export PATH=${PATH}:/usr/local/go/bin
系統啟動會自動執行這一指令碼
詳情見/etc/profile文本的內容:
# /etc/profile# System wide environment and startup programs, for login setup# Functions and aliases go in /etc/bashrc# It's NOT a good idea to change this file unless you know what you# are doing. It's much better to create a custom.sh shell script in# /etc/profile.d/ to make custom changes to your environment, as this# will prevent the need for merging in future updates.pathmunge () { case ":${PATH}:" in *:"$1":*) ;; *) if [ "$2" = "after" ] ; then PATH=$PATH:$1 else PATH=$1:$PATH fi esac}...for i in /etc/profile.d/*.sh ; do if [ -r "$i" ]; then if [ "${-#*i}" != "$-" ]; then . "$i" else . "$i" >/dev/null fi fidone
$- 代表當前shell的選項,See 1 2 3
echo "$-" 顯示的是 himBH (5個選項)
${-#*i} 中的*這裡是字串萬用字元,#這裡是字串操作符,${string#match_string}
Deletes shortest match of $match_string from front of $string. See 4
所以${-#*i} 是 mBH
但是,上述做法之後,在Terminal中echo $PATH中會出現兩次/usr/local/go/bin。雖然無傷大雅,但也挺奇怪的,難道這個指令碼被執行了兩次。
是的,被執行了兩次:
~/.bashrc -> /etc/bashrc 中也執行了一遍。
2)恰當的做法:
利用/etc/profile (/etc/bashrc)中定義的pathmunge 函數去除重複:
echo "pathmunge /usr/local/go/bin after" > custom.sh && chmod 755 custom.sh
5