常用腳本for 循環,和nginx的啟動
1)for循環示例
[root@game updata]# cat pvzgame_jar.sh #!/bin/bash SERVERS=( pvzgame_quick_001 pvzgame_quick_002 ) for var in ${SERVERS[@]} do mv /opt/htdocs/$var/${var}.jar /opt/htdocs/$var/${var}.jar.bak.2019.5.22 cp /root/updata/game_pvz_17-39.jar /opt/htdocs/$var/${var}.jar echo "文件更新完成:"$var done
2)nginx啟動腳本示例
#!/bin/bash # [ -e $PID ] -e 存在 PROCESS=/usr/local/nginx/sbin/nginx PID=/var/run/nginx.pid start(){ if [ -e $PID ];then echo -e "\033[34m nginx already running... \033[0m" else $PROCESS echo -e "\033[34m ngins start OK \033[0m" exit 0 fi } stop(){ if [ -e $PID ];then $PROCESS -s stop echo -e "\033[34m nginx stop OK ... \033[0m" else echo -e "\033[34m nginx not running... \033[0m" fi } reload(){ if [ -e $PID ];then $PROCESS -s reload echo -e "\033[34m nginx is reload ... \033[0m" else echo -e "\033[31m nginx not running ... \033[0m" fi } configtest(){ $PROCESS -t } status(){ if [ -e $PID ];then echo -e "\033[34m nginx already running... \033[0m" else echo -e "\033[31m nginx not running ... \033[0m" fi } case $1 in start) start ;; stop) stop ;; reload) reload ;; configtest) configtest ;; status) status ;; *) echo -e $"\033[31m Usage: $prog {start|stop|reload|configtest|status}\033[0m" ;; esac
一、if語句的使用
1)語法規則
if [條件]
then
指令
fi
或
if [條件];then
指令
fi
提示:分號相當於命令換行,上面兩種語法等同
特殊寫法;if[ -f"$file1" ];then echo 1;fi 相當於[ -f"$file1" ] && echo 1
2)多分支結構語法
多分支結構;語法 if 條件 then 指令集 elif 條件 #多個 then 指令集 else 指令集 fi
3)比較大小的案例
案例一,交互式的
#!/bin/sh
read -p "pls input two num:" a b
if [ $a -lt $b ];then
echo "yes,$a less than $b"
exit
fi
if [ $a -eq $b ];then
echo "yes,$a eaual than $b"
exit
fi
if [ $a -gt $b ];then
echo "yes,$a greater than $b"
exit
fi
案例二,命令行輸入比較大小
[root@tomcat day1]# cat ifif.sh
#!/bin/sh
a=$1
b=$2
[ $# -ne 2 ] && {
echo "USAGE:$0 NUM1 NUM2"
exit 1
}
expr $a + 0 &>/dev/null
RETVAL1=$?
expr $b + 0 &>/dev/null
RETVAL2=$?
test $RETVAL1 -eq 0 -a $RETVAL2 -eq 0 ||{
echo "Pla input two intnum again"
exit 2
}
if [ $a -lt $b ]
then
echo "$a < $b"
elif [ $a -eq $b ]
then
echo "$a = $b"
else
echo "$a > $b"
fi
exit 0
案例三,比較大小經典版
[root@oldboy66 day2]# cat if_else.sh
#!/bin/sh
if [ $1 -eq $2 ]
then
echo "$1=$2"
exit
elif [ $1 -gt $2 ]
then
echo "$1>$2"
exit
else
echo "$1<$2"
exit
fi
4)判定在特定目錄下創建文件的案例
[root@oldboy66 day2]# cat if4.sh
#!/bin/sh
path=/server/scripts
file=if3.sh
if [ ! -d $path ];then
mkdir -p $path
echo "$path is not exist,already created it."
fi
if [ ! -f $path/$file ];then
touch $path/$file
echo "$path/$file is not exist,already created it."
exit
fi
echo "ls -l $path/$file"
ls -l $path/$file
5)查看內存,測試郵件報警
1)安裝sendmail郵件工具
yum install sendmail -y
/etc/init.d/sendmail start
2)獲取內存大小
[root@oldboy66 day2]# free -m
total used free shared buffers cached
Mem: 980 906 73 0 135 489
-/+ buffers/cache: 282 698
Swap: 511 0 511
[root@oldboy66 day2]# free -m|grep buffers/
-/+ buffers/cache: 281 698
[root@oldboy66 day2]# free -m|grep buffers/|awk '{print $NF}'
698
3)寫入腳本
[root@oldboy66 day3]# cat check_mem.sh
#!/bin/sh
used_men=`free -m|awk 'NR==3 {print $NF}'`
if [ $used_men -lt 800 ];then
echo "men is not enough,$used_men"
echo "men is not enough.$used_men."|mail -s "men warning $(date +%F)" 1111111111@qq.com
fi
4)qq郵箱設置
打開qq郵箱===》“設置” ====》“反垃圾”=====》
“設置郵件地址白名單”=====》添加“root@tomcat.localdomain”
5)執行腳本,收到郵件
6)寫入定時任務
[root@oldboy66 ~]# crontab -e
###發郵件mail,mutt。Sendmail服務要開啟,定時任務報警
*/3 * * * * /bin/sh /server/scripts/day3/check_mem.sh &>/dev/null
二、檢測mysql服務是否啟動,如果沒啟動,就去啟動
1)檢測思路
netstat -lntup|grep 3306 看端口 ps -ef|grep mysql 看進程 mysql -u root -p123456 -S /data/3307/mysql.sock -e "select version();" (多實例)登錄進去看版本取返回值 +-----------+ | version() | +-----------+ | 5.5.32 | +-----------+ mysql -u root -poldboy -S /data/3307/mysql.sock -e "select version();" &>/dev/null echo $?
2)檢測啟動腳本
方法一;根據端口
mysql單實例檢測端口 [root@tomcat ]# cat port.sh #!/bin/sh port=`netstat -lntup|grep 3306|wc -l` if [ $port -ne 1 ] then /etc/init.d/mysqld start else echo "MySQL is running" fi
方法二;根據進程
mysql檢測進程 [root@tomcat ]# cat process.sh #!/bin/sh process=`ps -ef|grep mysql|grep -v grep|wc -l` if [ $process -ne 2 ] then /etc/init.d/mysqld start else echo "MySQL is running" fi ### sh -x process.sh #注意事項 調試。使用進程腳本不要用到mysql的名字
三、檢查web服務是否啟動
1)簡單的檢查web是否啟動
[root@linux day3]# cat check_web.sh
#!/bin/sh
http_code=`curl -I -s -w "%{http_code}" -o /dev/null 192.168.1.50:50080`
if [ $http_code -ne 200 ]
then
echo "web is error"
else
echo "web is ok"
fi
2)利用系統函數,實現腳本啟動的特殊顏色效果,開發web服務的啟動腳本
[root@linux day4]# cat start_nginx.sh
#!/bin/sh
. /etc/init.d/functions
if [ $# -ne 1 ]
then
echo "USAGE $0 {start|stop|restart}"
exit 1
fi
if [ "$1" == "start" ]
then
action "start nginx" /bin/true
elif [ "$1" == "stop" ]
then
action "stop nginx" /bin/true
elif [ "$1" == "restart" ]
then
action "restart nginx" /bin/true
else
echo "USAGE $0 {start|stop|restart}"
exit 1
fi
3)增加函數功能,實現上面的例子
[root@linux day4]# cat start_nginx02.sh
#!/bin/sh
. /etc/init.d/functions
start_nginx=/application/nginx/sbin/nginx
USAGE()
{
echo "USAGE $0 {start|stop|restart}"
exit 1
}
if [ $# -ne 1 ]
then
USAGE
fi
if [ "$1" == "start" ]
then
$start_nginx
action "start nginx" /bin/true
elif [ "$1" == "stop" ]
then
killall nginx
action "stop nginx" /bin/true
elif [ "$1" == "restart" ]
then
pkill nginx
sleep 2
$start_nginx
action "restart nginx" /bin/true
else
USAGE
exit 1
fi
四、shell函數
1)函數語法
shell函數語法
函數名()
{
指令
return n
}
或
function 函數名()
{
指令
return n
}
2)函數說明
【函數帶參數的說明】 1:函數體中位置參數($1、$2、$3、$4、$5、$#、$*、$?以及$@)都可以是函數的參數 2:父腳本的參數則臨時地被函數參數所掩蓋或隱藏 3:$0比較特殊,它仍然是父腳本的名稱 4:當函數完成時,原來的命令行參數會恢復 5:在shell函數里面,return命令的功能的工作方式與exit相同,用於跳出函數 6:在shell函數體里使用exit會終止整個shell腳本 7:return語句會返回一個退出值給調用的程序
3)函數調用例子
[root@linux day4]# cat fun01.sh
#!/bin/sh
oldboy01(){
echo "I am caojin linux"
}
oldboy01
[root@linux day4]# sh fun01.sh
I am caojin linux
4)函數傳參,判斷web服務是否正常
[root@linux day4]# cat check_web_by_fun.sh
#!/bin/sh
function Check_Url()
{
curl -I -s $1 |head -1 && return 0||return 1
}
Check_Url $1
[root@linux day4]# sh check_web_by_fun.sh 192.168.1.50:50080
HTTP/1.1 200 OK
[root@linux day4]# sh check_web_by_fun.sh baidu.com
HTTP/1.1 200 OK
五、開發mysql·的啟動腳本
1)簡單版
已知mysql多實例啟動命令為:mysqld_safe --defaults-file=/data/3306/my.cnf & 停止命令為:mysqladmin -u root -p123 -S /data/3306/mysql.sock shutdown ============================================================================= 下面是單實例腳本 #!/bin/sh . /etc/init.d/functions path="/application/mysql/bin" function usage(){ echo "$0 {start|stop|restart}" exit 1 } [ $# -ne 1 ] && usage function start_mysql(){ $path/mysqld_safe --user=mysql & if [ $? -eq 0 ] then action "start mysql" /bin/true else action "start mysql" /bin/false fi } function stop_mysql(){ mysqladmin -u root -p123456 shutdown if [ $? -eq 0 ] then action "stop mysql" /bin/true else action "stop mysql" /bin/false fi } if [ "$1" == "start" ] then start_mysql elif [ "$1" == "stop" ] then stop_mysql elif [ "$1" == "restart" ] then stop_mysql sleep 2 start_mysql else usage fi
2)優化版,去掉mysql的啟動輸出
#!/bin/sh . /etc/init.d/functions # chkconfig: 2345 21 60 # description: start mysql and stop mysql scripts path="/application/mysql/bin" user=root pass=123456 function usage(){ echo "$0 {start|stop|restart}" exit 1 } [ $# -ne 1 ] && usage function start_mysql(){ $path/mysqld_safe --user=mysql >dev/null 2>&1 & if [ $? -eq 0 ] then action "start mysql" /bin/true else action "start mysql" /bin/false fi } function stop_mysql(){ mysqladmin -u$user -p$pass shutdown >dev/null 2>&1 if [ $? -eq 0 ] then action "stop mysql" /bin/true else action "stop mysql" /bin/false fi } if [ "$1" == "start" ] then start_mysql elif [ "$1" == "stop" ] then stop_mysql elif [ "$1" == "restart" ] then stop_mysql sleep 2 start_mysql else usage fi
3)添加到開機啟動
1)測試OK 2)cp start_db.sh /etc/init.d/mysqld 3)chmod +x /etc/init.d/mysqld 4)chkconfig --list mysqld 5)chkconfig --add mysqld 6)chkconfig mysqld on 7)chkconfig --list mysqld 8)ll /etc/rc.d/rc3.d/|grep mysqld
# chkconfig: 2345 21 60 #2345 啟動級別, #21 開機啟動順序, # 60 關機順序
六、輸出顏色方法
1)echo 輸出字符串顯示不同顏色范例
echo -e "\033[30m 黑色字caojin tarinning \033[0m" echo -e "\033[31m 紅色字caojin tarinning \033[0m" echo -e "\033[32m 綠色字caojin tarinning \033[0m" echo -e "\033[33m 黃色字caojin tarinning \033[0m" echo -e "\033[34m 藍色字caojin tarinning \033[0m" echo -e "\033[35m 紫字caojin tarinning \033[0m" echo -e "\033[36m 天藍字caojin tarinning \033[0m" echo -e "\033[37m 白色字caojin tarinning \033[0m"
2)字背景顏色范圍:40------47
echo -e "40;37m 黑底白字 whlcome to China\033[0m" echo -e "41;37m 黑底白字 whlcome to China\033[0m" echo -e "42;37m 黑底白字 whlcome to China\033[0m" echo -e "43;37m 黑底白字 whlcome to China\033[0m" echo -e "44;37m 黑底白字 whlcome to China\033[0m" echo -e "45;37m 黑底白字 whlcome to China\033[0m" echo -e "46;37m 黑底白字 whlcome to China\033[0m" echo -e "47;30m 黑底白字 whlcome to China\033[0m"
3)簡單顏色腳本
[root@oldboy66 day4]# cat echo-color.sh #!/bin/bash RED_COLOR='\E[1;31m' GREEN_COLOR='\E[1;32m' YELLOW_COLOR='\E[1;33m' BLUE_COLOR='\E[1;34m' PINK='\E[1;35m' RES='\E[0m' echo -e "${RED_COLOR}====red color===={$RES}" echo -e "${YELLOW_COLOR}====yellow color===={$RES}" echo -e "${BLUE_COLOR}====blue color===={$RES}" echo -e "${GREEN_COLOR}====green color===={$RES}" echo -e "${PINK}====pink color===={$RES}"
七、case結構條件句
1)基本語法
case "字符串變量" in 值1)指令1... ;; 值2)指令2... ;; *)指令... esac
2)case創建水果菜單,增加特殊顏色
[root@linux day4]# cat fruit_menu.sh #!/bin/sh RED_COLOR='\E[1;31m' GREEN_COLOR='\E[1;32m' YELLOW_COLOR='\E[1;33m' BLUE_COLOR='\E[1;33m' RES='\E[0m' menu(){ cat <<END ========== 1.apple 2.pear 3.banana 4.exit ========= END } while true do menu read -p "pls input your choice:" fruit case "$fruit" in 1) echo -e "$RED_COLOR apple $RES" ;; 2) echo -e "$GREEN_COLOR pear $RES" ;; 3) echo -e "$YELLOW_COLOR banana $RES" ;; 4) exit 0 ;; *) echo -e "no fruit you choose." esac done
3)利用傳參的形式給對象增加顏色
[root@oldboy66 day4]# cat plus_color.sh #!/bin/bash RED_COLOR='\E[1;31m' GREEN_COLOR='\E[1;32m' YELLOW_COLOR='\E[1;33m' BLUE_COLOR='\E[1;34m' PINK='\E[1;35m' RES='\E[0m' if [ $# -ne 2 ];then echo "Usage $0 content {red|yellow|blue|green}" exit fi case "$2" in red|RED) echo -e "${RED_COLOR}$1${RES}" ;; green|RED) echo -e "${GREEN_COLOR}$1${RES}" ;; yellow|RED) echo -e "${YELLOW_COLOR}$1${RES}" ;; blue|RED) echo -e "${BLUE_COLOR}$1${RES}" ;; pink|RED) echo -e "${PINK_COLOR}$1${RES}" ;; *) echo "Usage $0 content {red|yellow|blue|green}" exit esac
4)案例開發類似於rsync的啟動腳本
例如:/etc/init.d/rsynd {start|stop|restart}
[root@oldboy66 etc]# rsync --daemon
[root@oldboy66 etc]# lsof -i :873
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
rsync 6056 root 4u IPv4 22839 0t0 TCP *:rsync (LISTEN)
rsync 6056 root 5u IPv6 22840 0t0 TCP *:rsync (LISTEN)
[root@oldboy66 etc]# cat /var/run/rsyncd.pid
6056 目的生成pid 根據pid來做操作
[root@oldboy66 day5]# cat rsyncd.sh
#!/bin/sh
pidfile="/var/run/rsyncd.pid"
start_rsync(){
if [ -f "$pidfile" ]
then
echo "rsync is running"
else
rsync --daemon
echo "rsync is started"
fi
}
stop_rsync(){
if [ -f $pidfile ]
then
kill -USR2 `cat $pidfile`
rm -f ${pidfile}
echo "rsync is stopped"
else
echo "rsync have already been stopped"
fi
}
case "$1" in
start)
start_rsync
RETVAL=$?
;;
stop)
stop_rsync
RETVAL=$?
;;
restart)
stop_rsync
sleep 2
start_rsync
RETVAL=$?
;;
*)
echo "USACE:$0 {start|stop|restart}"
exit 1
esac
exit $RETVAL
注意:此腳本並不完善,可以加載函數,添加顏色,讓其開機自啟動(chkconfig)
八、while循環,以及until循環
1)while語法
while 條件句 do 指令... done
2)until語法
until 條件 do 指令.... done
3)while循環,守護進程舉例
提示:while true表示永遠為真,因此會一直運行,像死循環一樣,但是我們稱呼為守護進程
[root@linux day5]# cat while.sh #!/bin/sh while true do uptime sleep 2 done
腳本在后台執行
腳本在后台執行知識擴展: 功能 用途 sh while.sh & 把腳本while.sh放到后台執行 ctrl+c 停止執行當前腳本或任務 ctrl+z 暫停執行當前腳本或任務 bg 把當前腳本或任務放到后台執行 background fg 當前腳本或任務拿到前台執行,如果
如果執行的腳本忘記在后台執行
[root@oldboy66 day5]# sh while.sh ^Z [1]+ Stopped sh while.sh [root@oldboy66 day5]# bg [1]+ sh while.sh & [root@oldboy66 day5]#
4)while計算1加到100的和
方法一
[root@linux day5]# cat while_sum.sh #!/bin/sh i=1 sum=0 while [ $i -le 100 ] do let sum=sum+i let i=i+1 done echo $sum [root@oldboy66 day5]# sh while_sum.sh 5050
方法二
[root@linux day5]# sh while_sum.sh 5050 或 [root@oldboy66 day5]# cat while_sum2.sh #!/bin/sh i=1 sum=0 while ((i < 101)) do ((sum=sum+i)) ((i++)) done echo $sum
5)計算Apache一天的日志access_2016-12-8.log中所有行的日志各元素的訪問字節數的總和。給出實現程序。用while循環實現
[root@linux day5]# cat log.sh
#!/bin/sh
sum=0
i=0
while read line
do
i=$(echo $line|awk '{print $10}')
if expr $i + 0 &>/dev/null
then
((sum=sum+i))
fi
done <access_2015_12_8.log
echo $sum
6)while循環做抓鬮小游戲
要求:
[ 1 ]每個人都輸入名字,然后隨機產生不同的數字(1--99)
[ 2 ]第一個輸入名字后,屏幕輸出信息,並將名字和數字記錄到文件里,程序不能退出,繼續等待別的學生輸入。
[ 3 ]輸出的名字與對應的數字的最大則是被抓到的人
http://oldboy.blog.51cto.com/2561410/1308647 [root@localhost test]# cat za.sh #!/bin/sh [ ! -f file ] && touch file while true; do read -p '輸入:' you if [ -n "$you" ] && ! egrep "^$you.*" file;then while true; do rannum=$(expr $RANDOM % 99 + 1) if ! egrep "$you number is $rannum" file ;then echo "$you number is $rannum" >> file break fi done if [ "$you" == 'exit' ];then break fi fi done [root@localhost test]# sh za.sh 輸入:asd 輸入:qwe 輸入:asd asd number is 40 輸入:qwe qwe number is 1 輸入:
七、rsync 數據同步
范例:每10秒鍾做一次rsync binlog推送,通過守護進程方式,寫完腳本后台執行。當配好rsync服務時,可以直接用的腳本
[root@linux day5]# cat rsync_binlog.sh #!/bin/sh while true do rsync -az /data/3306/mysql-bin* rsync_backup@192.168.1.49::backup --password-file=/etc/rsync.password & sleep 10 done
八、for循環
1)for循環簡單例子
[root@linux day6]# cat for.sh #!/bin/sh for n in 5 4 3 2 1 do echo $n done
2)開發腳本實現僅設置sshd rsyslog crond network sysstat開機自啟動
[root@linux day6]# cat auto_start.sh
#!/bin/sh
for name in `chkconfig --list|grep 3:on|awk '{print $1}'`
do
chkconfig $name off
done
for name in rsyslog network crond sshd systtat
do
chkconfig $name on
done
3)for循環在/oldboy目錄下批量創建10個文件,名稱依次為:oldboy-1.html.....
[root@linux day6]# cat for_mkdir.sh
#!/bin/sh
[ ! -d /oldboy ] && mkdir -p /oldboy
for i in `seq 10`
do
touch /oldboy/oldboy-${i}.html
done
4)用for循環實現將以上文件名中的oldboy全部改為Linux,並且擴展名改為大寫。要求for循環的循環體不能出現oldboy字符串
[root@linux day6]# cat for_xiugai.sh #!/bin/sh for i in `seq 10` do cd /oldboy mv oldboy-$i.html linux-$i.HTML done 或 [root@linux day6]# cat for_xiugai2.sh #!/bin/sh cd /oldboy for f in `ls *.html` do # mv $f `echo $f|sed 's#oldboy#linux#g'|sed 's#html#HTML#g'` mv $f `echo $f|sed 's#oldboy\(.*\).html#linux\1.HTML#g'` done
批量改名案例:http://oldboy.blog.51cto.com/2561410/711342
5)批量創建10個用戶並設置密碼
[root@linux day6]# cat for_mima.sh #!/bin/sh for n in `seq -w 10` do useradd oldboy$n &&\ echo "root$n"|passwd --stdin oldboy$n done 或 [root@linux day6]# cat for_mima2.sh #!/bin/sh for n in `seq -w 10` do useradd oldboy$n -p root$n # userdel -r oldboy$n # useradd oldboy$n &&\ # echo "root$n"|passwd --stdin oldboy$n done
九、隨機數
1)獲取隨機數的7個方法
[root@linux day6]# echo $RANDOM [root@linux day6]# openssl rand -base64 8 [root@linux day6]# date +%s%N [root@linux day6]# head /dev/urandom|cksum [root@linux day6]# cat /proc/sys/kernel/random/uuid [root@linux day6]# yum install expect -y [root@linux day6]# mkpasswd -l 8
2)生產隨機數
[root@oldboy66 day6]# echo $RANDOM 17123 [root@oldboy66 day6]# echo $RANDOM 23696 [root@oldboy66 day6]# echo $((RANDOM+10000000)) 10028068 [root@oldboy66 day6]# echo $((RANDOM+10000000)) 10016282 [root@oldboy66 day6]# echo $RANDOM|md5sum|cut -c 1-8 100764b3 [root@oldboy66 day6]# echo $RANDOM|md5sum|cut -c 1-8 3447b18d 下面是高級隨機 [root@oldboy66 day6]# echo "`date`$RANDOM"|md5sum|cut -c 1-8 c78d73a8 [root@oldboy66 day6]# echo "`date`$RANDOM"|md5sum|cut -c 1-8 82d4b31e
