該腳本中運用到工做中經常使用的shell語法,瑣碎的語法結合起來能夠幫助處理工做,解放人力。nginx
主要經常使用的shell知識點:web
判斷參數是否存在和判斷參數個數shell
聲明函數api
判斷字符串相等數組
判斷字符串包含bash
判斷數組內容和數組個數,並循環數組服務器
if多條件語法app
sed
運維
記錄該腳本,是爲了記錄一些基礎語法,將來忘了能夠翻閱。 把基礎的語法運用得當,更好的協助運維的工做。腳本只適用一些特殊需求。ide
#!/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