Shell脚本的学习心得和知识总结(三)| shell语句

2020年2月29日16:19:01
从今天开始,就开始来写真正的shell了!

流程控制

流程控制是改变程序运行顺序的一些指令语句。linux shell有一套自己的流程控制语句,其中包括条件语句(if),循环语句(for,while,until),选择语句(case)等语句

if语句

我们昨天最后也是写了一个if语句的例子,下面来看一下其具体格式:

格式:if list; then list; [ elif list; then list; ] ... [ else list; ] fi

if语句主要分为三种:单分支、双分支和多分支

单分支

if 条件表达式; then

命令(条件满足之后,做的事情)

fi
[root@localhost myshell_study]# vim test1.sh
[root@localhost myshell_study]# cat test1.sh 
#!/bin/bash
if [ $1 -eq 1 ];then                 #单分支
	echo "你输入的第一个参数是$1"
fi

#--------------------------------------------
if [ $1 -eq 1 ]
then echo "你输入的第一个参数是$1"
fi
#--------------------------------------------
if [ $1 -eq 1 ]
then 
	echo "你输入的第一个参数是$1"
fi
[root@localhost myshell_study]# bash test1.sh 1
你输入的第一个参数是1
你输入的第一个参数是1
你输入的第一个参数是1
[root@localhost myshell_study]# bash test1.sh 2
[root@localhost myshell_study]# 

双分支

if 条件表达式; then
  命令
else
  命令
fi
[root@localhost myshell_study]# 
[root@localhost myshell_study]# cat test1.sh 
#!/bin/bash
if [ $1 -eq 1 ];then                 #双分支
	echo "你输入的第一个参数是$1"
else echo "你输入的第一个参数不是1"
fi

#--------------------------------------------
if [ $1 -eq 1 ]
then echo "你输入的第一个参数是$1"
else 
	echo "你输入的第一个参数不是1"
fi
#--------------------------------------------
if [ $1 -eq 1 ]
then 
	echo "你输入的第一个参数是$1"
else 
	echo "你输入的第一个参数不是1"
fi
[root@localhost myshell_study]# bash test1.sh 1
你输入的第一个参数是1
你输入的第一个参数是1
你输入的第一个参数是1
[root@localhost myshell_study]# bash test1.sh 2
你输入的第一个参数不是1
你输入的第一个参数不是1
你输入的第一个参数不是1
[root@localhost myshell_study]# 

判断crond进程是否正在运行
背景如下:

[root@localhost myshell_study]# ps aux | grep "crond" 
root       4619  0.0  0.0 112712   960 pts/1    S+   16:54   0:00 grep --color=auto crond
[root@localhost myshell_study]# systemctl start crond
[root@localhost myshell_study]# ps aux | grep "crond" 
root       4642 45.5  0.0 126288  1672 ?        Ss   16:54   0:00 /usr/sbin/crond -n
root       4649  0.0  0.0 112712   960 pts/1    S+   16:54   0:00 grep --color=auto crond
[root@localhost myshell_study]# ps aux | grep "crond" | grep -v "color"
root       4642  2.3  0.0 126288  1672 ?        Ss   16:54   0:00 /usr/sbin/crond -n
[root@localhost myshell_study]# ps aux | grep "crond" | grep -v "color" | wc -l
1
[root@localhost myshell_study]# 

上面若是进程在运行之中,值就是1

[root@localhost myshell_study]# cat check.sh 
#!/bin/bash
status_num=`ps aux | grep "crond" | grep -v "grep" | wc -l`
echo $status_num
soft=crond
if [ "$status_num" -eq 1 ];then 
	echo "$soft在运行中!"
else 
	echo "$soft不在运行!"
fi
[root@localhost myshell_study]# bash check.sh 
1
crond在运行中!
[root@localhost myshell_study]# 
[root@localhost myshell_study]# systemctl stop crond
[root@localhost myshell_study]# bash check.sh 
0
crond不在运行!
[root@localhost myshell_study]# 

检查主机是否在线
如下:

[root@localhost myshell_study]# vim check_host.sh
[root@localhost myshell_study]# cat check_host.sh 
#!/bin/bash
ip=192.168.124.5
ping -c 1 -w 1 $ip &>/dev/null  #-c 1 是一次一个包;-w 1是等待超市时间1秒 后面的意思是:把正确和错误的输出结果都发送到黑洞文件中去。好处是 不用再看到命令执行后的输出结果
if [ $? -eq 0 ];then
	echo "$ip is online!"
else echo "$ip is offline"
fi

#----------------------------------
ping -c 1 -w 1 $1 &>/dev/null  #-c 1 是一次一个包;-w 1是等待超市时间1秒 后面的意思是:把正    确和错误的输出结果都发送到黑洞文件中去。好处是 不用再看到命令执行后的输出结果
if [ $? -eq 0 ];then
    echo "$1 is online!"
else echo "$1 is offline"
fi

[root@localhost myshell_study]# bash check_host.sh 192.168.124.11
192.168.124.5 is online!
192.168.124.11 is offline
[root@localhost myshell_study]# ping 192.168.124.5
PING 192.168.124.5 (192.168.124.5) 56(84) bytes of data.
64 bytes from 192.168.124.5: icmp_seq=1 ttl=64 time=95.0 ms
64 bytes from 192.168.124.5: icmp_seq=2 ttl=64 time=116 ms
^C
--- 192.168.124.5 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 95.090/105.850/116.611/10.765 ms
[root@localhost myshell_study]# ping 192.168.124.11
PING 192.168.124.11 (192.168.124.11) 56(84) bytes of data.
From 192.168.124.20 icmp_seq=1 Destination Host Unreachable
From 192.168.124.20 icmp_seq=2 Destination Host Unreachable
From 192.168.124.20 icmp_seq=3 Destination Host Unreachable
From 192.168.124.20 icmp_seq=4 Destination Host Unreachable
^C
--- 192.168.124.11 ping statistics ---
5 packets transmitted, 0 received, +4 errors, 100% packet loss, time 4003ms
pipe 4
[root@localhost myshell_study]# 

注:上面的黑洞文件的目的 就是给用户一个良好的体验,而不是把所有的打印信息都给用户显示出来!

多分支

if 条件表达式; then
  命令
elif 条件表达式; then  #elif  表达式当然也可以有多个
  命令
else
  命令
fi

注:当不确定条件符合哪一个时,就可以把已知条件判断写出来,做相应的处理。

[root@localhost myshell_study]# vim num.sh
[root@localhost myshell_study]# cat num.sh 
#! /bin/bash
read -p "please input a number:" number
if [ $number -le 5 ];then
	echo "the number $number is not greater than 5!"
elif [ $number -gt 5 -a $number -le 10 ];then
	echo "the number $number is greater than 5,but it is not greater than 10!"
elif [ $number -gt 10 -a $number -le 20 ];then
    echo "the number $number is greater than 10,but it is not greater than 20!"
else echo "the number $number is greater than 20!"
fi

[root@localhost myshell_study]# bash num.sh 
please input a number:4
the number 4 is not greater than 5!
[root@localhost myshell_study]# bash num.sh 
please input a number:14
the number 14 is greater than 10,but it is not greater than 20!
[root@localhost myshell_study]# bash num.sh 
please input a number:24
the number 24 is greater than 20!
[root@localhost myshell_study]# 

实现文件的拷贝
背景如下:
需求:

  1. 完成用户输入文件或者目录的自动复制,并可以实现用户指定复制目标位置。
  2. 用户体验佳。

Linux的 cp命令 详解

[root@localhost myshell_study]# vim copyfile.sh 
[root@localhost myshell_study]# cat copyfile.sh 
#! /bin/bash
read -p "请你输入一个你想要拷贝的文件或者目录:" file
if [ -f $file -o -d $file ];then
	read -p "你真的要拷贝这个文件或目录吗?(y/n)" character
	status_char=$(echo ${character} | tr A-Z a-z)
	if [ "$status_char" == y ];then
		read -p "目标路径为:" path
		if [ -d $path ];then 
			cp -a $file $path
			echo "文件 $file 复制到路径$path成功!"
		else 
			echo "你输入的路径非法!"
			exit 1
		fi
	elif [ "$status_char" == n ];then
		echo "不复制拉倒!"
	else "你特么在干啥?输入y/n,玛德智障!"
	fi
else echo "你输入的文件或者目录非法!"
fi
[root@localhost myshell_study]# bash copyfile.sh 
请你输入一个你想要拷贝的文件或者目录:./hello.sh
你真的要拷贝这个文件或目录吗?(y/n)N
不复制拉倒!
[root@localhost myshell_study]# bash copyfile.sh 
请你输入一个你想要拷贝的文件或者目录:./hello.sh
你真的要拷贝这个文件或目录吗?(y/n)y
目标路径为:/root
文件 ./hello.sh 复制到路径/root成功!
[root@localhost myshell_study]# 
[root@localhost myshell_study]# bash copyfile.sh 
请你输入一个你想要拷贝的文件或者目录:./hello.sh
你真的要拷贝这个文件或目录吗?(y/n)666
copyfile.sh: line 17: 你特么在干啥?输入y/n,玛德智障!: No such file or directory
[root@localhost myshell_study]# bash copyfile.sh 
请你输入一个你想要拷贝的文件或者目录:/root/myshell/
你真的要拷贝这个文件或目录吗?(y/n)Y
目标路径为:/root/myshell_study
文件 /root/myshell/ 复制到路径/root/myshell_study成功!
[root@localhost myshell_study]# ls
copyfile.sh  hello.sh  myshell
[root@localhost myshell_study]# 

实现简单计算器,实现加减乘除
背景如下:
需求:

请输入一个数字: 7

请输入运算符:+

请输入第二个数字:7

7+7=14
[root@localhost myshell_study]# vim Calculator.sh
[root@localhost myshell_study]# cat Calculator.sh 
#!/bin/bash
                       #----------------#
                       # 我的简易计算器   #
                       #----------------#
read -p "请输入第一个数字      :" num1
read -p "请输入进行计算的运算符 :" char
read -p "请输入第二个数字      :" num2

if [ -n "$num1" -a -n "$char" -a -n "num2" ];then
	if [ "$char" == "+" ];then
		echo "${num1}${char}${num2}=$((num1+num2))"
	elif [ "$char" == "-" ];then
        echo "${num1}${char}${num2}=$((num1-num2))"
    elif [ "$char" == "*" ];then
        echo "${num1}${char}${num2}=$((num1*num2))"
    elif [ "$char" == "/" ];then
        echo "${num1}${char}${num2}=$((num1/num2))"
	else echo "你输的操作符是啥玩意儿?"
	fi
elif [ -z "$num1" -o -z "num2" ];then
	echo "你输的数字为空,不能进行计算"
else echo "你没有输入运算符,我咋给你计算?"
fi
[root@localhost myshell_study]# bash Calculator.sh 
请输入第一个数字      :4
请输入进行计算的运算符:+
请输入第二个数字      :2
4+2=6
[root@localhost myshell_study]# bash Calculator.sh 
请输入第一个数字      :4
请输入进行计算的运算符:-
请输入第二个数字      :2
4-2=2
[root@localhost myshell_study]# bash Calculator.sh 
请输入第一个数字      :4
请输入进行计算的运算符:*
请输入第二个数字      :2
4*2=8
[root@localhost myshell_study]# bash Calculator.sh 
请输入第一个数字      :4
请输入进行计算的运算符:/
请输入第二个数字      :2
4/2=2
[root@localhost myshell_study]# bash Calculator.sh 
请输入第一个数字      :4
请输入进行计算的运算符:
请输入第二个数字      :2
你没有输入运算符,我咋给你计算?
[root@localhost myshell_study]# bash Calculator.sh 
请输入第一个数字      :
请输入进行计算的运算符:+
请输入第二个数字      :2
你输的数字为空,不能进行计算
[root@localhost myshell_study]# bash Calculator.sh 
请输入第一个数字      :
请输入进行计算的运算符:
请输入第二个数字      :
你输的数字为空,不能进行计算
[root@localhost myshell_study]#
[root@localhost myshell_study]# bash Calculator.sh 
请输入第一个数字      :4
请输入进行计算的运算符:f
请输入第二个数字      :2
你输的操作符是啥玩意儿?

输入一个用户,用脚本判断判断该用户是否存在

[root@localhost myshell_study]# id song
id: song: no such user
[root@localhost myshell_study]# id uxdb
uid=1000(uxdb) gid=1000(uxdb) groups=1000(uxdb),18(dialout)
[root@localhost myshell_study]# id root
uid=0(root) gid=0(root) groups=0(root)
[root@localhost myshell_study]# id oracle
uid=1001(oracle) gid=1002(dba) groups=1002(dba)
[root@localhost myshell_study]# vim check_user.sh
[root@localhost myshell_study]# cat check_user.sh 
#!/bin/bash

read -p "请输入一个用户:" user
if id $user &>/dev/null;then
	echo "$user 存在"
else echo "$user 不存在"
fi
[root@localhost myshell_study]# bash check_user.sh 
请输入一个用户:song
song 不存在
[root@localhost myshell_study]# bash check_user.sh 
请输入一个用户:oracle
oracle 存在
[root@localhost myshell_study]# bash check_user.sh 
请输入一个用户:uxdb
uxdb 存在
[root@localhost myshell_study]# bash check_user.sh 
请输入一个用户:root
root 存在
[root@localhost myshell_study]# 

for循环

for循环详解

其代码格式如下:

格式:for name [ [ in [ word ... ] ] ; ] do list ; done
------------------------------------------------------
for 变量名 in 取值列表; do
  命令
done
------------------------------------------------------
或者,下面也是可以的
------------------------------------------------------
for 变量名 in 取值列表
do
   命令
done

一个例子如下:

[root@localhost myshell_study]# vim print_num.sh
[root@localhost myshell_study]# cat print_num.sh 
#!/bin/bash
#目的:每个2秒进行一次打印输出

read -p "你想要打印到数字几?" num
for i in `seq $num`
do
	echo "数字$i"
	sleep 2        # 打印结束,睡上2秒
done
[root@localhost myshell_study]# bash print_num.sh 
你想要打印到数字几?5
数字1
数字2
数字3
数字4
数字5
[root@localhost myshell_study]#

计算100以内偶数和

[root@localhost myshell_study]# vim sum.sh
[root@localhost myshell_study]# cat sum.sh 
#!/bin/bash
# 计算100以内偶数和
sum=0
for i in `seq 0 2 100`
do
	let sum+=$i
done

echo "总和为:$sum"
[root@localhost myshell_study]# bash sum.sh 
总和为:2550

批量检测主机是否在线

[root@localhost myshell_study]# vim sum.sh
[root@localhost myshell_study]# cat sum.sh 
#!/bin/bash
# 批量检测主机是否在线
ip=192.168.124.
for i in {1..25}
do 
	if ping -c 1 -w 1 $ip$i &>/dev/null;then
		echo "当前主机 $ip$i  在线!"
	else
		echo "当前主机 $ip$i  不在线!"
	fi
done
[root@localhost myshell_study]# bash sum.sh 
当前主机 192.168.124.1  在线!
当前主机 192.168.124.2  在线!
当前主机 192.168.124.3  在线!
当前主机 192.168.124.4  在线!
当前主机 192.168.124.5  在线!
当前主机 192.168.124.6  不在线!
当前主机 192.168.124.7  不在线!
当前主机 192.168.124.8  不在线!
当前主机 192.168.124.9  不在线!
当前主机 192.168.124.10  在线!
当前主机 192.168.124.11  不在线!
当前主机 192.168.124.12  不在线!
当前主机 192.168.124.13  在线!
当前主机 192.168.124.14  不在线!
当前主机 192.168.124.15  不在线!
当前主机 192.168.124.16  不在线!
当前主机 192.168.124.17  不在线!
当前主机 192.168.124.18  不在线!
当前主机 192.168.124.19  不在线!
当前主机 192.168.124.20  在线!
当前主机 192.168.124.21  不在线!
当前主机 192.168.124.22  不在线!
当前主机 192.168.124.23  不在线!
当前主机 192.168.124.24  不在线!
当前主机 192.168.124.25  不在线!
[root@localhost myshell_study]# 

但是 这样看起来并不是很舒服,如下:

[root@localhost myshell_study]# vim sum.sh
[root@localhost myshell_study]# cat sum.sh 
#!/bin/bash
# 批量检测主机是否在线
. /etc/init.d/functions    # 这里面有很多的好用的函数,.是加载配置文件
ip=192.168.124.
for i in {1..25}
do 
	if ping -c 1 -w 1 $ip$i &>/dev/null;then
		echo -n "当前主机 $ip$i"   # -n是不换行
		success 
		echo "" #进行换行
	else
		echo -n "当前主机 $ip$i"
		failure
		echo ""
	fi
done
[root@localhost myshell_study]# bash sum.sh 
当前主机 192.168.124.1                                     [  OK  ]
当前主机 192.168.124.2                                     [  OK  ]
当前主机 192.168.124.3                                     [  OK  ]
当前主机 192.168.124.4                                     [  OK  ]
当前主机 192.168.124.5                                     [  OK  ]
当前主机 192.168.124.6                                     [FAILED]
当前主机 192.168.124.7                                     [FAILED]
当前主机 192.168.124.8                                     [FAILED]
当前主机 192.168.124.9                                     [FAILED]
当前主机 192.168.124.10                                    [  OK  ]
当前主机 192.168.124.11                                    [FAILED]
当前主机 192.168.124.12                                    [FAILED]
当前主机 192.168.124.13                                    [  OK  ]
当前主机 192.168.124.14                                    [FAILED]
当前主机 192.168.124.15                                    [FAILED]
当前主机 192.168.124.16                                    [FAILED]
当前主机 192.168.124.17                                    [FAILED]
当前主机 192.168.124.18                                    [FAILED]
当前主机 192.168.124.19                                    [FAILED]
当前主机 192.168.124.20                                    [  OK  ]
当前主机 192.168.124.21                                    [FAILED]
当前主机 192.168.124.22                                    [FAILED]
当前主机 192.168.124.23                                    [FAILED]
当前主机 192.168.124.24                                    [FAILED]
当前主机 192.168.124.25                                    [FAILED]
[root@localhost myshell_study]# 

判断当前目录下面的文件类型
背景:

[root@localhost myshell_study]# ll
total 4
lrwxrwxrwx. 1 root root   6 Mar  7 21:08 sum1.sh -> sum.sh
-rw-r--r--. 1 root root 322 Mar  7 20:13 sum.sh
drwxr-xr-x. 2 root root   6 Mar  7 21:08 test
[root@localhost myshell_study]# ll | grep -o ^.
t(这是total)
l               链接文件
-               普通文件类型 
d               目录文件 
[root@localhost myshell_study]#

脚本实例如下

[root@localhost myshell_study]# vim current_dir.sh 
[root@localhost myshell_study]# cat current_dir.sh 
#!/bin/bash
# 判断当前目录下面的文件类型
read -p "请输入一个需要判断的有效目录:" dir
for i in `ls -l $dir | grep -o ^.`
do
	echo -n "当前文件类型为:$i。" 
	if [ "$i" == "t" ];then
		echo  "什么类型也不是!"
	elif [ "$i" == "l" ];then
		echo "本文件类型为:链接文件!"
	elif [ "$i" == "-" ];then
		echo "本文件类型为:普通文件!"
	elif [ "$i" == "d" ];then
        echo "本文件类型为:目录文件!"
	else echo "本文件类型可能为其他文件类型!"
	fi
done
[root@localhost myshell_study]# bash current_dir.sh 
请输入一个需要判断的有效目录:.
当前文件类型为:t。什么类型也不是!
当前文件类型为:-。本文件类型为:普通文件!
当前文件类型为:l。本文件类型为:链接文件!
当前文件类型为:-。本文件类型为:普通文件!
当前文件类型为:d。本文件类型为:目录文件!
[root@localhost myshell_study]# ll
total 8
-rw-r--r--. 1 root root 547 Mar  7 21:42 current_dir.sh
lrwxrwxrwx. 1 root root   6 Mar  7 21:08 sum1.sh -> sum.sh
-rw-r--r--. 1 root root 322 Mar  7 20:13 sum.sh
drwxr-xr-x. 2 root root   6 Mar  7 21:08 test
[root@localhost myshell_study]# 
[root@localhost myshell_study]# ll ./test/
total 0 
[root@localhost myshell_study]# bash current_dir.sh 
请输入一个需要判断的有效目录:./test
当前文件类型为:t。什么类型也不是!
[root@localhost myshell_study]# 

while循环

while循环详解

其代码格式如下

格式:while list; do list; done
------------------------------
while 条件表达式; do
    命令(条件表达式为真 do命令)
done
[root@localhost myshell_study]# vim sum.sh 
[root@localhost myshell_study]# cat sum.sh 
#!/bin/bash
sum=0
while [ $sum -le 5 ]
do
	let sum+=1
	echo "当前sum的值为:$sum"
	sleep 1
done
[root@localhost myshell_study]# bash sum.sh 
当前sum的值为:1
当前sum的值为:2
当前sum的值为:3
当前sum的值为:4
当前sum的值为:5
当前sum的值为:6
[root@localhost myshell_study]# 

注:当上面条件表达式为 false 时,终止循环。然而在实际的需要中,我们常常需要死循环来实现一些功能:可以用来后台运行检测脚本 (一直运行)。
检测终端数量
背景:
在这里插入图片描述
现在当前终端在线:3个

[root@localhost myshell_study]# vim check_ter.sh
[root@localhost myshell_study]# cat check_ter.sh 
#!/bin/bash
while true
do 
	num=`who | wc -l`
	echo "当前终端个数:$num" >> ./terminal.log
	sleep 3 
done
[root@localhost myshell_study]# bash check_ter.sh &              --放在后台
[1] 3808
[root@localhost myshell_study]# kill 3808
[1]+  Terminated              bash check_ter.sh
[root@localhost myshell_study]# ls
check_ter.sh  sum.sh  terminal.log
[root@localhost myshell_study]# ls
check_ter.sh  sum.sh  terminal.log
[root@localhost myshell_study]# vim terminal.log 
当前终端个数:3
当前终端个数:3
当前终端个数:3
当前终端个数:3
当前终端个数:4    --复制ssh终端
当前终端个数:4
当前终端个数:5
当前终端个数:5
[root@localhost myshell_study]# nohup bash check_ter.sh &
[2] 4403
nohup: [1]   Terminated              nohup bash check_ter.sh
ignoring input and appending output to ‘nohup.out’
[root@localhost myshell_study]# kill 4403
[root@localhost myshell_study]# ls
check_ter.sh  nohup.out  sum.sh  terminal.log
[2]+  Terminated              nohup bash check_ter.sh
[root@localhost myshell_study]# cat nohup.out 
[root@localhost myshell_study]# 

使用 while 循环逐行读取文件
背景:

[root@localhost myshell_study]# vim read.sh
[root@localhost myshell_study]# cat read.sh 
#!/bin/bash
#---------------------------第一种---------------
number=0
cat /etc/passwd | while read a_line
do
	if [ $number -lt 3 ];then
		echo $a_line
		sleep 2
		let number+=1
	fi
done
number=0
#---------------------------第二种---------------
while read b_line
do
	if [ $number -lt 3 ];then
		echo $b_line
		sleep 2
		let number+=1
	fi
done < /etc/passwd #标准输入重定向
number=0
#---------------------------第三种--------------- 
exec < /etc/passwd #读取文件作为标准输出
while read c_line
do
	if [ $number -lt 3 ];then
		echo $c_line
		sleep 2
		let number+=1
	fi
done
[root@localhost myshell_study]# bash read.sh 
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
[root@localhost myshell_study]# 

until 语句

until 语句详解

注:until 语句:与 while 不同之处在于,是当条件表达式为 false 时才循环。
其代码格式如下:

格式:until list; do list; done
------------------------------
until 条件表达式; do
    命令(条件表达式为假 do命令)
done
[root@localhost myshell_study]# vim sum.sh 
[root@localhost myshell_study]# cat sum.sh 
#!/bin/bash
sum=0
until [ $sum -ge 5 ]  大于等于5为假:即小于5为真
do
	let sum+=1
	echo "当前sum的值为:$sum"
done
[root@localhost myshell_study]# bash sum.sh 
当前sum的值为:1
当前sum的值为:2
当前sum的值为:3
当前sum的值为:4
当前sum的值为:5
[root@localhost myshell_study]# 

注:上面until大于等于5为假,可以看做是while语句的小于5为真。

break & continue语句

break & continue 语句详解

注:这点和我们的C(C++)有点一样的意味。break 是终止循环。continue 是跳出当前(本次)循环。 当然他们也只能使用在循环语句当中!

[root@localhost myshell_study]# vim test1.sh
[root@localhost myshell_study]# cat test1.sh 
#!/bin/bash
sum=0
while true
do
	let sum+=1
	if [ $sum -eq 5 ];then
		echo "sum数值已经到达5"
		break
	fi
done
echo "--------------------------"
while true
do
	let sum--
	if [ $sum -eq 4 ];then
		echo "sum数值现在是4"
		continue
	fi
if [ $sum == 0 ];then
	exit
fi
done
[root@localhost myshell_study]# bash test1.sh 
sum数值已经到达5
--------------------------
sum数值现在是4
[root@localhost myshell_study]# 

case语句

case 语句详解

case 语句一般用于选择性来执行对应部分块命令。其代码格式 如下:

case 模式名    in
模式 1)
  命令
  ;;                           结尾以双分号结束一个段
模式 2)
  命令
  ;;
*)
  不符合以上模式执行的命令
esac

注:每个模式必须以右括号结束,命令结尾以双分号结束,最后一个模式不需要添加;;

[root@localhost myshell_study]# vim operator.sh 
[root@localhost myshell_study]# cat operator.sh 
#!/bin/bash
read -p "请输入你想要的行为:(start | stop | restart | status)-->"  cmd_str
case $cmd_str in
start)
		systemctl start httpd &>/dev/null 
		echo "httpd has started" ;;
stop)
		systemctl stop httpd &>/dev/null
		echo "httpd has stopped" ;;
restart)
		systemctl restart httpd &>/dev/null 
		echo "httpd has restarted" ;;
status)
		systemctl status httpd &>/dev/null ;;
*)
		echo "你输入的是啥玩意儿啊"
		echo "Usage: $0 start | stop | restart | status"
esac
[root@localhost myshell_study]# bash operator.sh 
请输入你想要的行为:(start | stop | restart | status)-->start
httpd has started
[root@localhost myshell_study]# ps -ef | grep http
root       2450      1  0 05:01 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache     2452   2450  0 05:01 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache     2453   2450  0 05:01 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache     2454   2450  0 05:01 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache     2455   2450  0 05:01 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache     2456   2450  0 05:01 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
root       2468   1911  0 05:01 pts/0    00:00:00 grep --color=auto http
[root@localhost myshell_study]# ss -tnl
State      Recv-Q Send-Q   Local Address:Port                  Peer Address:Port              
LISTEN     0      128                  *:111                              *:*                  
LISTEN     0      5        192.168.122.1:53                               *:*                  
LISTEN     0      128                  *:22                               *:*                  
LISTEN     0      128          127.0.0.1:631                              *:*                  
LISTEN     0      100          127.0.0.1:25                               *:*                  
LISTEN     0      128          127.0.0.1:6010                             *:*                  
LISTEN     0      128                 :::111                             :::*                  
LISTEN     0      128                 :::80                              :::*                  
LISTEN     0      128                 :::22                              :::*                  
LISTEN     0      128                ::1:631                             :::*                  
LISTEN     0      100                ::1:25                              :::*                  
LISTEN     0      128                ::1:6010                            :::*                  
[root@localhost myshell_study]# bash operator.sh 
请输入你想要的行为:(start | stop | restart | status)-->stop
httpd has stopped
[root@localhost myshell_study]# ss -tnl
State      Recv-Q Send-Q   Local Address:Port                  Peer Address:Port              
LISTEN     0      128                  *:111                              *:*                  
LISTEN     0      5        192.168.122.1:53                               *:*                  
LISTEN     0      128                  *:22                               *:*                  
LISTEN     0      128          127.0.0.1:631                              *:*                  
LISTEN     0      100          127.0.0.1:25                               *:*                  
LISTEN     0      128          127.0.0.1:6010                             *:*                  
LISTEN     0      128                 :::111                             :::*                  
LISTEN     0      128                 :::22                              :::*                  
LISTEN     0      128                ::1:631                             :::*                  
LISTEN     0      100                ::1:25                              :::*                  
LISTEN     0      128                ::1:6010                            :::*                  
[root@localhost myshell_study]# bash operator.sh 
请输入你想要的行为:(start | stop | restart | status)-->666
你输入的是啥玩意儿啊
Usage: operator.sh start | stop | restart | status
[root@localhost myshell_study]# 

根据不同类型的参数匹配不同的模式
背景:

[root@localhost myshell_study]# vim datatype.sh
[root@localhost myshell_study]# cat datatype.sh
#!/bin/bash
echo "-----------------------------------"
read -p "请输入你所需要判断的数据=》" data
echo "-----------------------------------"
case $data in
[0-9])
	echo "$data 的数据类型是 数字";;
[a-z])
	echo "$data 的数据类型是 小写字母";;
[A-Z])
	echo "$data 的数据类型是 大写字母";;
*)
	echo "$data 的数据类型是 你猜猜看"
	exit
esac
[root@localhost myshell_study]# bash datatype.sh
-----------------------------------
请输入你所需要判断的数据=》6
-----------------------------------
6 的数据类型是 数字
[root@localhost myshell_study]# bash datatype.sh
-----------------------------------
请输入你所需要判断的数据=》s
-----------------------------------
s 的数据类型是 小写字母
[root@localhost myshell_study]# bash datatype.sh
-----------------------------------
请输入你所需要判断的数据=》S
-----------------------------------
S 的数据类型是 小写字母
[root@localhost myshell_study]# bash datatype.sh
-----------------------------------
请输入你所需要判断的数据=》$
-----------------------------------
$ 的数据类型是 你猜猜看
[root@localhost myshell_study]#

乘法口诀表
背景:

[root@localhost myshell_study]# vim computing.sh
[root@localhost myshell_study]# cat computing.sh 
#!/bin/bash
for i in `seq 9`
do
	for j in `seq 9`
	do
		if [ $i -le $j ];then
			result=$((i*j))
			if [ $result -lt 10 ];then
				echo -n "$i*$j=$((i*j))  "
			else echo -n "$i*$j=$((i*j)) "
			fi
		fi
	done
	echo ""
done
[root@localhost myshell_study]# bash computing.sh 
1*1=1  1*2=2  1*3=3  1*4=4  1*5=5  1*6=6  1*7=7  1*8=8  1*9=9  
2*2=4  2*3=6  2*4=8  2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 
3*3=9  3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27 
4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36 
5*5=25 5*6=30 5*7=35 5*8=40 5*9=45 
6*6=36 6*7=42 6*8=48 6*9=54 
7*7=49 7*8=56 7*9=63 
8*8=64 8*9=72 
9*9=81 
[root@localhost myshell_study]# 

监测内存剩余量
背景:

[root@localhost myshell_study]# free -h
              total        used        free      shared  buff/cache   available
Mem:           1.8G        376M        863M        9.2M        583M        1.2G
Swap:          2.0G          0B        2.0G
[root@localhost myshell_study]# 
[root@localhost myshell_study]# free -h
              total        used        free      shared  buff/cache   available
Mem:           1.8G        376M        863M        9.2M        583M        1.2G
Swap:          2.0G          0B        2.0G
[root@localhost myshell_study]# free -h | grep Mem | cut -d "M" -f 3
        862
[root@localhost myshell_study]# free -h | grep Mem | cut -d "M" -f 3 | tr -d " "
862
[root@localhost myshell_study]# 

代码如下:

[root@localhost myshell_study]# vim check_free.sh
[root@localhost myshell_study]# cat check_free.sh 
#!/bin/bash
while [ 1 -eq 1 ]
do
	free_size=$(free -h | grep Mem | cut -d "M" -f 3 | tr -d " ")
	if [ $free_size -gt 500 ];then
		#mail -s "当前内存剩余量低于预警值!"
		echo "当前内存剩余量大于预警值!"
		break
	fi
done
[root@localhost myshell_study]# nohup bash check_free.sh &
[1] 3729
[root@localhost myshell_study]# nohup: ignoring input and appending output to ‘nohup.out’

[1]+  Done                    nohup bash check_free.sh
[root@localhost myshell_study]# bash check_free.sh 
当前内存剩余量大于预警值!
[root@localhost myshell_study]# 

2020年3月15日06:02:30

猜你喜欢

转载自blog.csdn.net/weixin_43949535/article/details/104576428