运维shell全部语法进阶

一、if语句的使用

1)语法规则

1
2
3
4
5
6
7
8
9
if [条件]
    then
        指令
fi
if [条件];then
    指令
fi
提示:分号相当于命令换行,上面两种语法等同<br>特殊写法;if[ -f"$file1" ];then echo 1;fi 相当于[ -f"$file1" ] && echo 1

2)多分支结构语法

1
2
3
4
5
6
7
8
9
10
多分支结构;语法
if 条件
  then
    指令集
elif 条件       #多个
  then
    指令集
else
    指令集
fi  

3)比较大小的案例

   案例一,交互式的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/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

  案例二,命令行输入比较大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[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

案例三,比较大小经典版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[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)判定在特定目录下创建文件的案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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)检测思路

1
2
3
4
5
6
7
8
9
10
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)检测启动脚本

方法一;根据端口

1
2
3
4
5
6
7
8
9
10
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

方法二;根据进程

1
2
3
4
5
6
7
8
9
10
11
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是否启动

1
2
3
4
5
6
7
8
9
[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服务的启动脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[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)增加函数功能,实现上面的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[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)函数语法

1
2
3
4
5
6
7
8
9
10
11
12
shell函数语法
函数名()
{
    指令
    return n
}
function 函数名()
{
    指令
    return n
}

2)函数说明

1
2
3
4
5
6
7
8
【函数带参数的说明】
1:函数体中位置参数($1、$2、$3、$4、$5、$#、$*、$?以及$@)都可以是函数的参数
2:父脚本的参数则临时地被函数参数所掩盖或隐藏
3:$0比较特殊,它仍然是父脚本的名称
4:当函数完成时,原来的命令行参数会恢复
5:在shell函数里面,return命令的功能的工作方式与exit相同,用于跳出函数
6:在shell函数体里使用exit会终止整个shell脚本
7:return语句会返回一个退出值给调用的程序

3)函数调用例子

1
2
3
4
5
6
7
8
[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服务是否正常

1
2
3
4
5
6
7
8
9
10
11
[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)简单版

 View Code

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

 View Code

3)添加到开机启动

1
2
3
4
5
6
7
8
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 输出字符串显示不同颜色范例

1
2
3
4
5
6
7
8
echo -e "33[30m 黑色字caojin tarinning 33[0m"
echo -e "33[31m 红色字caojin tarinning 33[0m"
echo -e "33[32m 绿色字caojin tarinning 33[0m"
echo -e "33[33m 黄色字caojin tarinning 33[0m"
echo -e "33[34m 蓝色字caojin tarinning 33[0m"
echo -e "33[35m 紫字caojin tarinning 33[0m"
echo -e "33[36m 天蓝字caojin tarinning 33[0m"
echo -e "33[37m 白色字caojin tarinning 33[0m"

2)字背景颜色范围:40------47

1
2
3
4
5
6
7
8
echo -e "40;37m 黑底白字 whlcome to China33[0m"
echo -e "41;37m 黑底白字 whlcome to China33[0m"
echo -e "42;37m 黑底白字 whlcome to China33[0m"
echo -e "43;37m 黑底白字 whlcome to China33[0m"
echo -e "44;37m 黑底白字 whlcome to China33[0m"
echo -e "45;37m 黑底白字 whlcome to China33[0m"
echo -e "46;37m 黑底白字 whlcome to China33[0m"
echo -e "47;30m 黑底白字 whlcome to China33[0m"

3)简单颜色脚本

 View Code

七、case结构条件句

1)基本语法

1
2
3
4
5
6
7
case "字符串变量" in
    值1)指令1...
;;
    值2)指令2...
;;
    *)指令...
esac

2)case创建水果菜单,增加特殊颜色

 View Code

3)利用传参的形式给对象增加颜色

 View Code

4)案例开发类似于rsync的启动脚本

 View Code

注意:此脚本并不完善,可以加载函数,添加颜色,让其开机自启动(chkconfig)

 八、while循环,以及until循环

1)while语法

1
2
3
4
while 条件句
    do
    指令...
done

2)until语法

1
2
3
4
until 条件
    do
    指令....
done

3)while循环,守护进程举例

提示:while true表示永远为真,因此会一直运行,像死循环一样,但是我们称呼为守护进程

1
2
3
4
5
6
7
[root@linux day5]# cat while.sh
#!/bin/sh
while true
do
   uptime
   sleep 2
done

脚本在后台执行

1
2
3
4
5
6
7
脚本在后台执行知识扩展:
功能          用途
sh while.sh &       把脚本while.sh放到后台执行
ctrl+c          停止执行当前脚本或任务
ctrl+z          暂停执行当前脚本或任务
bg          把当前脚本或任务放到后台执行  background
fg          当前脚本或任务拿到前台执行,如果

如果执行的脚本忘记在后台执行

1
2
3
4
5
6
7
[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的和

方法一

1
2
3
4
5
6
7
8
9
10
11
12
[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

方法二

1
2
3
4
5
6
7
8
9
10
11
12
13
[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循环实现

1
2
3
4
5
6
7
8
9
10
11
12
13
[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 ]输出的名字与对应的数字的最大则是被抓到的人

 View Code

七、rsync 数据同步

范例:每10秒钟做一次rsync binlog推送,通过守护进程方式,写完脚本后台执行。当配好rsync服务时,可以直接用的脚本

1
2
3
4
5
6
7
[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循环简单例子

1
2
3
4
5
6
[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开机自启动

1
2
3
4
5
6
7
8
9
10
[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.....

1
2
3
4
5
6
7
[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字符串

 View Code

批量改名案例:http://oldboy.blog.51cto.com/2561410/711342

5)批量创建10个用户并设置密码

 View Code

九、随机数

1)获取随机数的7个方法

1
2
3
4
5
6
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)生产随机数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[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
原文地址:https://www.cnblogs.com/duanlinxiao/p/10789242.html