该脚本中运用到工作中常用的shell语法,琐碎的语法结合起来可以帮助处理工作,解放人力。
主要常用的shell知识点:
- 判断参数是否存在和判断参数个数
- 声明函数
- 判断字符串相等
- 判断字符串包含
- 判断数组内容和数组个数,并循环数组
- if多条件语法
- sed
记录该脚本,是为了记录一些基础语法,未来忘了可以翻阅。 把基础的语法运用得当,更好的协助运维的工作。脚本只适用一些特殊需求。
#!/bin/bash
# 2017/1/11
#适用添加m站点的脚本。 将域名 改变成目录代理的方式。
LIST=`echo "$1" | cut -d. -f1`
LISTER=`echo "$1" | cut -d. -f2`
oldnip=`echo "$3" | sed ‘s/\// /g‘`
nip=($oldnip)
PORT="$2"
HOST=$(hostname)
#判断是否在nginx服务器主机上执行,并由于目录不一致,而声明了两个不同变量
if [ $HOST = "tnginx101" ];then
ROUTE="/app/nginx"
elif [ $HOST = "tnginx102" ];then
ROUTE="/usr/local/nginx"
else
echo "$HOST not nginx proxy"
exit 2
fi
DIRECTORY="/app/shell/mtemplate/msite"
TEMPLATE="/app/shell/mtemplate"
MPROXY="$ROUTE/conf/Directory"
#判断参数个数是否正确
if [ -z $1 ] && [ -z $2 ] && [ -z $3 ];then
echo "Please input three arguments"
echo "Usage: $basename$0 content.m.mallcoo.cn 9001 web101/web102"
exit 2
fi
if [ $# -ne 3 ];then
echo "input arguments error"
exit 2
fi
if [ ! -d $MPROXY ];then
echo "not exist $MPROXY"
exit 3
fi
if [ ! -d $DIRECTORY ] ;then
echo "not exist "$DIRECTORY""
exit 2
fi
upstream_http(){
if [ $LISTER = "m" ];then
cat $TEMPLATE/upstream_template > $DIRECTORY/Server-Port.conf
sed -i ‘s/template_template_http/‘$LIST‘_m_http/g‘ $DIRECTORY/Server-Port.conf
if [ ${#nip[@]} -gt 1 ];then
for i in ${nip[*]};do
sed -i ‘/upstream/a\ server ‘$i‘:‘$PORT‘ weight=2 max_fails=2 fail_timeout=30s;‘ $DIRECTORY/Server-Port.conf
done
elif [ ${#nip[@]} -eq 1 ];then
sed -i ‘/upstream/a\ server ‘$nip‘:‘$PORT‘ weight=2 max_fails=2 fail_timeout=30s;‘ $DIRECTORY/Server-Port.conf
else
echo "please confirm it "
exit 2
fi
cat $DIRECTORY/Server-Port.conf >> $MPROXY/Server-Port.conf
fi
#匹配域名 第二节 包含api的字符。如content.api.mallcoo.cn
if [[ $LISTER =~ "api" ]];then
cat $TEMPLATE/upstream_template > $DIRECTORY/Server-Port.conf
sed -i ‘s/template_template_http/‘$LIST‘_api_http/g‘ $DIRECTORY/Server-Port.conf
if [ ${#nip[@]} -gt 1 ];then
for i in ${nip[*]};do
sed -i ‘/upstream/a\ server ‘$i‘:‘$PORT‘ weight=2 max_fails=2 fail_timeout=30s;‘ $DIRECTORY/Server-Port.conf
done
elif [ ${#nip[@]} -eq 1 ];then
sed -i ‘/upstream/a\ server ‘$nip‘:‘$PORT‘ weight=2 max_fails=2 fail_timeout=30s;‘ $DIRECTORY/Server-Port.conf
else
echo "please confirm it "
exit 2
fi
cat $DIRECTORY/Server-Port.conf >> $MPROXY/Server-Port.conf
fi
}
#追加 location_http
location_http(){
if [ $LISTER = "m" ];then
cat $TEMPLATE/location_template > $DIRECTORY/Http.conf
sed -i ‘s/mould\/mould/a\/‘$LIST‘/g‘ $DIRECTORY/Http.conf
sed -i ‘s/template_template_http/‘$LIST‘_m_http/g‘ $DIRECTORY/Http.conf
cat $DIRECTORY/Http.conf >> $MPROXY/Http.conf
fi
if [[ $LISTER =~ "api" ]];then
cat $TEMPLATE/location_template > $DIRECTORY/Http.conf
sed -i ‘s/mould\/mould/api\/‘$LIST‘/g‘ $DIRECTORY/Http.conf
sed -i ‘s/template_template_http/‘$LIST‘_api_http/g‘ $DIRECTORY/Http.conf
cat $DIRECTORY/Http.conf >> $MPROXY/Http.conf
fi
}
upstream_http
location_http