2007-12-14
Linux和Unix下新建、删除环境变量的脚本
建立环境变量的脚本。变量建立在当前用户的配置文件里,XXX_HOME为要建立的变量名,tochage为变量值。
删除环境变量的脚本(从当前用户的配置文件里删除)
虽然很简单,但写这个脚本的时候还是学到了些东西。比如一般的用户的配置文件可能分.bash_profile、.bash_login、.profile这几种,以及用sed '/某字符串/d' 文件名可以删除文件中包含某个字符串的行,将结果输出到屏幕上(不会直接写文件)。另外,如果此时直接将内容重定向回要操作的文件,可能会导致文件内容丢失。所以可以先把内容保存到一个临时文件里,然后在覆盖要操作的文件。
cd ~ XXX_HOME=tochage export XXX_HOME if [ -f ".bash_profile" ] then echo "">>.bash_profile echo "XXX_HOME=$XXX_HOME">>.bash_profile echo "export XXX_HOME">>.bash_profile elif [ -f ".bash_login" ] then echo "">>.bash_login echo "XXX_HOME=$XXX_HOME">>.bash_login echo "export XXX_HOME">>.bash_login else echo "">>.profile echo "XXX_HOME=$XXX_HOME">>.profile echo "export XXX_HOME">>.profile fi
删除环境变量的脚本(从当前用户的配置文件里删除)
cd ~
unset XXX_HOME
if [ -f ".bash_profile" ]
then
sed '/XXX_HOME/d' .bash_profile > .bash_profile.tempforinforsuite
cat .bash_profile.tempforinforsuite > .bash_profile
elif [ -f ".bash_login" ]
then
sed '/XXX_HOME/d' .bash_login > .bash_login.tempforinforsuite
cat .bash_login.tempforinforsuite > .bash_login
else
sed '/XXX_HOME/d' .profile > .profile.tempforinforsuite
cat .profile.tempforinforsuite > .profile
fi
虽然很简单,但写这个脚本的时候还是学到了些东西。比如一般的用户的配置文件可能分.bash_profile、.bash_login、.profile这几种,以及用sed '/某字符串/d' 文件名可以删除文件中包含某个字符串的行,将结果输出到屏幕上(不会直接写文件)。另外,如果此时直接将内容重定向回要操作的文件,可能会导致文件内容丢失。所以可以先把内容保存到一个临时文件里,然后在覆盖要操作的文件。


评论