一、问题的提出
我的实验环境是开了一个Ubuntu的虚拟机,想给它配置个代理,由于我想让使用该虚拟机的所有用户都能使用代理,所以我首先切换到root用户,然后进入到/etc/profile.d目录下(至于我为什么不直接修改/etc/profile文件请自行查阅了解),我新建一个proxy.sh文件,使用vim编辑,内容如下:
export proxy="http://192.168.124.6:1080"
export http_proxy=$proxy
export https_proxy=$proxy
export ftp_proxy=$proxy
export no_proxy="localhost,127.0.0.1,::1"
然后,以root用户的身份,执行
source /etc/profile
接着我使用
curl www.google.com
发现能够愉快地“出去”。
接着我退出root用户,回到普通用户,发现刚刚的环境变量的设置并未对普通用户有效(也就是说,我的代理对于普通用户来说没有设置成功),于是乎,我立马以普通用户的身份打开一个终端,执行
source /etc/profile
然后也能愉快地“出去”,但是问题是,当以普通用户的身份重新打开一个终端时,先前设置的环境变量已经失效了。
二、解决方案
2.1 重启Ubuntu即可。
2.2 将上述配置写在~/.bashrc中
2.3 在~/.bashrc中最后加入source /etc/profile
三、解决后的思考
3.1 /etc/profile
它是一个文件,不建议修改它里面的内容,它里面的内容默认如下:
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).
if [ "${PS1-}" ]; then
if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
# The file bash.bashrc already sets the default PS1.
# PS1='\h:\w\$ '
if [ -f /etc/bash.bashrc ]; then
. /etc/bash.bashrc
fi
else
if [ "`id -u`" -eq 0 ]; then
PS1='# '
else
PS1='$ '
fi
fi
fi
if [ -d /etc/profile.d ]; then
for i in /etc/profile.d/*.sh; do
if [ -r $i ]; then
. $i
fi
done
unset i
fi
只有当Login-Shell(或者你显示地使用source /etc/profile)才会去运行这个脚本,而Non-login Shell不会调用这个脚本。
通过读这个文件的内容可知,在/etc/profile里面设置的变量都是系统级别的、对所有用户有效的全局的变量,而且这个脚本会去调用/etc/profile.d/目录下的所有的.sh脚本文件。
3.2 /etc/profile.d/
它是一个目录,存放的是一些应用程序所需的启动脚本(.sh),而这些脚本文件是用来设置一些变量和运行一些初始化过程的。其中包括了颜色、语言、less、vim及which等命令的一些附加设置。
/etc/profile.d 下的脚本之所以能自动执行,是因为在/etc/profile 中有一个for循环语句来调用这些脚本
四、概括总结
使用login方式是会读取 /etc/profile文件 和~/.profile文件。使用non login方式的话,会读取/etc/bash.bashrc 文件和 ~/.bashrc文件的内容。