Linux运维之shell脚本进阶篇

时间:2021-12-29 19:16:53

常用脚本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.
cp /root/updata/game_pvz_17-.jar /opt/htdocs/$var/${var}.jar
echo "文件更新完成:"$var
done

for循环更改文件

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
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 $ 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

nginx

一、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//my.cnf &
停止命令为:mysqladmin -u root -p123 -S /data//mysql.sock shutdown
=============================================================================
下面是单实例脚本
#!/bin/sh
. /etc/init.d/functions
path="/application/mysql/bin"
function usage(){
echo "$0 {start|stop|restart}"
exit
}
[ $# -ne ] && usage function start_mysql(){
$path/mysqld_safe --user=mysql &
if [ $? -eq ]
then
action "start mysql" /bin/true
else
action "start mysql" /bin/false
fi
}
function stop_mysql(){
mysqladmin -u root -p123456 shutdown
if [ $? -eq ]
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
start_mysql
else
usage
fi

2)优化版,去掉mysql的启动输出

#!/bin/sh
. /etc/init.d/functions
# chkconfig:
# description: start mysql and stop mysql scripts
path="/application/mysql/bin"
user=root
pass=
function usage(){
echo "$0 {start|stop|restart}"
exit
}
[ $# -ne ] && usage function start_mysql(){
$path/mysqld_safe --user=mysql >dev/null >& &
if [ $? -eq ]
then
action "start mysql" /bin/true
else
action "start mysql" /bin/false
fi
}
function stop_mysql(){
mysqladmin -u$user -p$pass shutdown >dev/null >&
if [ $? -eq ]
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
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
==========
.apple
.pear
.banana
.exit
=========
END
}
while true
do menu
read -p "pls input your choice:" fruit
case "$fruit" in
)
echo -e "$RED_COLOR apple $RES"
;;
)
echo -e "$GREEN_COLOR pear $RES"
;;
)
echo -e "$YELLOW_COLOR banana $RES"
;;
)
exit
;;
*)
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 ];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 :
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
rsync root 4u IPv4 0t0 TCP *:rsync (LISTEN)
rsync root 5u IPv6 0t0 TCP *:rsync (LISTEN)
[root@oldboy66 etc]# cat /var/run/rsyncd.pid
目的生成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
start_rsync
RETVAL=$?
;;
*)
echo "USACE:$0 {start|stop|restart}"
exit
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 % + )
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
输入:qwe
qwe number is
输入:

七、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 `
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 `
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 `
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