使用shell脚本修改环境变量

1.添加环境变量add.sh


#!/bin/sh
if [ $# -eq 1 ];then
    str=$1;
else
    echo "no env to be added!"
    exit 0
fi

if ! echo $PATH|grep -q $str;then echo "export PATH=$str:$PATH" >>/etc/profile  ;fi

2.删除环境变量del.sh


#!/bin/sh
TPATH=$PATH
if [ $# -eq 1 ];then
    str=$1;
else
    echo "no env to be deleted!"
    exit 0
fi
if ! echo $str|grep -q ":";then
    if echo $TPATH|grep -q $str":";then
        TPATH=${TPATH//$str":"/}
    elif echo $TPATH|grep -q ":"$str;then
        TPATH=${TPATH//":"$str/}
    fi
else
    TPATH=${TPATH//$str/}
fi

echo "export PATH=$TPATH" >> /etc/profile

3.脚本使用

source add.sh addenv

source del.sh delenv