1)第一次尝试的天真做法:
以注册golang环境变量为例:
cd /etc/profile.d
ls -rtl
touch custom.sh # or any file name you like to create a new file
ls -rtl
echo "export PATH=\${PATH}:/usr/local/go/bin" > custom.sh && chmod 755 custom.sh
less custom.sh
. custom.sh
echo $PATH
reboot
不建议直接写入/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
fi
done
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