Linux环境变量的备份与恢复

在Linux开发过程中对环境变量的修改是难免的,手工修改环境变量痛苦不言而喻,而export也只能影响到当前shell的。在脚本中修改的变量只能通过source才能使父shell生效。自己写了一个备份环境变量和恢复的脚本,有待完善,但能用。

BAK="env.bak"

function bak(){
    echo "export PATH=$PATH" > ${BAK}
    echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH" >> ${BAK}
    echo "export SDGHOME=$SDGHOME" >> ${BAK}
    echo "export Oracle_HOME=$ORACLE_HOME" >> ${BAK}
}

function change(){
    AR=$1
    RE=`sed -n '/${AR}=/'p ${RC}`
    RB="export `sed -n '/${AR}=/'p ${BAK}`"
    if [ "${RE}" == "" ];then
        echo ${RB} >> ${RC}
    else
        sed -i "s/^\(${AR}=\).*/&${RB}" >> ${RC}
    fi 
}

function restore(){
    RC=~/.bashrc
    change "PATH"
    change "LD_LIBARY_PAHT"
    change "SDGHOME"
    change "ORACLE_HOME"
}

short_options="b:r:n"
long_options="back:,restore:,name:"

opts=`getopt -o $short_options --long $long_options`

case $1 in
    -b|--back)
        echo "back enviroment, you can use \"source ${BAK}\" use bak enviroment"
        bak
        ;;
    -r|--restore)
        echo "restore enviroment for [[`whoami`]],you must user new show,enable this enviroment"
        restore
        ;;
    -n|--name)
        BAK=$1
        ;;
    *)
        echo "Internal error!"
        exit 1
        ;;
esac

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/0b26880a49c3b90017cf7e000e9b9156.html