放置在 /etc/profile.d/env.sh
#Normal-ENV
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
export TZ='Asia/Shanghai'
export APP_HOME=/data
#Path-ENV
ENV_PATH=()
ENV_PATH[${#ENV_PATH[@]}]=APP_PATH:/data/app/bin
for item in ${ENV_PATH[@]};
do
path_name=${item#*:}
path_value=${item##*:}
found=0
pathlist=(${PATH//:/ })
for pathitem in ${pathlist[@]}
do
if [ "$pathitem" == "$path_value" ];then
found=1
break
fi
done
if [ $found -ne 1 ];then
PATH=$PATH:$path_value
fi
done
export PATH
放置在 /bin/set-path
#!/bin/bash
KEY=$1
VALUE=$2
if [ -z $KEY ]; then
echo "key not found!"
exit 1
fi
if [ -z $VALUE ]; then
echo "value not found!"
exit 1
fi
#查看环境变量是否已存在
COUNT=`sed -n '/'$KEY'_PATH:/p' /etc/profile.d/env.sh | wc -l`
#对VALUE中的"/"增加转义符为"\\/"
VALUE=`echo "$VALUE" | sed -s "s/\//\\\\\\\\\//g"`
if [ $COUNT -ge 1 ];then
#如果存在,则修改
sed -i "s/"$KEY"_PATH:.*$/"$KEY"_PATH:"$VALUE"/g" /etc/profile.d/env.sh
else
#如果不存在,则添加
sed -i "/ENV_PATH=()/a\ENV_PATH[\${\#ENV_PATH[\@]}]="$KEY"_PATH:"$VALUE /etc/profile.d/env.sh
fi
#使其生效
source /etc/profile
为该文件添加执行权限:chmod +x ./set-path
示例运行:
$ set-path scala /usr/local/scala/bin // 将scala/bin 添加到环境变量
$ source /etc/profile
网友评论