Shell Script applications (2)

By Bowen Shell script application (a) , can be all kinds of statements will be executed in the order followed a simple Shell script in order to automate batch process, however, a single sequence structure makes the script Mandarin mechanization, not "smart "difficult to deal with a more flexible system tasks.

Today we will learn how to recognize and conditional test operation, and through the proper use of the if statement, the Shell scripts have a certain "judgment" capability, according to different conditions to complete various administrative tasks.

A, which test

For Shell script has some "intelligence", the first problem faced is how to distinguish between different situations has been determined what to do with. For example: When disk usage reaches a certain point, a warning message and other operations.

Shell environment according to the return status value ($?) After the command is executed successfully performed to determine whether, when the return value of 0 indicates success; when the return value is not zero, it indicates a failure. The use of specialized testing tools --test command, can be tested for specific conditions.

When tested using the test command, two syntaxes:

格式1:test  条件表达式

or

格式2:[  条件表达式  ]

The role of these two methods are identical, but usually the second syntax is more applicable.
But note: The second syntax format in brackets "[or]" with the conditional expression requires at least a space separated!

Depending on the type of condition to be tested, the conditional expression is different, relatively common condition comprises:

1. File Test

Refers to a test file according to a specific path, it determines the corresponding file is a directory or a file, or whether to read, write, execute other operations. Commonly used options are:

-d:测试是否为目录(Directory)
-e:测试目录或文件是否存在(Exist)
-f:测试是否为文件(File)
-r:测试当前用户是否有权限读取(Read)
-w:测试当前用户是否有权限写入(Write)
-x:测试当前用户是否有权限执行(eXcute)

After performing the test operation condition, by a pre-defined variable $? Command to get the return value of the test is to determine if the condition is satisfied. such as:

[root@localhost ~]# [ -d /mnt ]                         //测试/mnt是不是一个目录
[root@localhost ~]# echo $?                           //查看前一条命令的返回值
0                                                                     //0表示条件成立,非0则表示条件不成立

For a more intuitive view test results, may be combined with "&&" and "echo" commands. such as:

[root@localhost ~]# [ -d /etc ] && echo "yes"
yes                 //输出“yes”表示条件成立,不输出“yes”则表示条件不成立

2. Comparative integer

It refers to an integer value according to the comparison given two integer values, determining the relationship between the first number and the second number, such as equal to, greater than, less than or equal. Commonly used options are:

-eq:等于(Equal)
-ne:不等于(Not Equal)
-gt:大于(Greater Than)
-lt:小于(Lesser Than)
-le:小于或等于(Lesser or Equal)
-ge:大于或等于(Greater or Equal)

Shell prepared in Comparative integer toluene more applications. For example, to determine the number of users logged in, open the number of processes and so on. such as:

[root@localhost ~]# A=`who | wc -l`
[root@localhost ~]# [ $A -eq 3 ] && echo "nice"
nice            //查看当前登录用户为3的话输出“nice”

3. string comparison

String comparisons are typically hard ah checks the user input, the system meets the environmental conditions in providing interactive operation S I back script may be used to determine the position of the user input parameters to meet the requirements. Commonly used parameters are:

=:字符串内容相同
!=:字符串内容不同,! 号表示相反的意思
-z:字符串内容为空

Syntax:

[  字符串1  =  字符串2 ]
[  字符串1  !=  字符串2 ]
[  -z  字符串 ]

4. Logic Test

It refers to a logical test by determining the relationship between the lazy two or more conditions. When the system task depends on a number of different conditions, these conditions are established at the same time or one set up, etc., the need for a testing process parameters are used:

-a或&&:逻辑与,“而且”的意思
-o或||:逻辑或,“或者”的意思
!:逻辑否

Syntax:

格式1:[  表达式1  ]  操作符  [  表达式2  ]  ... 
格式2:命令1  操作符  命令2  ... 

Second, if statement structure

Just by simple conditional tests can be done to determine and implement the appropriate Cao group, but when there are many to choose command statement executed, this approach makes the code look complicated and difficult to understand. We can use if appropriate statement, to organize the structure of the script, so that structured, clear and easy to understand.

1) the structure of the if statement

Shell script application, if the statement is the most common kind of flow control, force ah according to the specific conditions of the test results, respectively, to perform different actions (if ...... so ......). Depending on the complexity, selection structure if statement can be divided into three basic types, suitable for different applications.

1. Single-branch if statement

if statement: "branch" refers to the results of various tests performed corresponding statements (one or more). For if choice but branching structure, only if "conditions are met" will execute the corresponding code, or do nothing.

1) single-branch if statement syntax structure:

if 
条件测试操作
then 
命令序列
fi

Sentence structure, which test may be "[Conditional Expression]" statement, and may be other statements specified command, command sequence means that one or more executable command line, including nested if used statement or other flow control statements.

2) a single branch of the if statement Flowchart:

Shell Script applications (2)

3) Application example of a single branch of the if statement:

[root@localhost ~]# vim a.sh                            //随便定义脚本名称
#!/bin/bash                                                       //声明使用什么Shell
A="/mnt/cdrom"                                               //定义变量
if                                                                       //关键字(如果)
[ !-d $A ]                                                 //$A变量不是一个目录的话
then                                                                  //关键字(那么)
mkdir -p $A                                              //创建这个变量所对应的目录
fi                                                                      //关键字(结束)
[root@localhost ~]# sh a.sh                            //执行脚本
[root@localhost ~]# ll /mnt                               
总用量 0
drwxr-xr-x. 2 root root 6 7月  30 12:19 cdrom                //验证效果

2. The multi-branch if statement

The choice of multi-branch structure, the requirements for the "establishment of conditions", "conditions are not met," the two cases perform different operations, respectively.

1) dual-branch if the grammatical structure of the sentence:

if 
条件测试操作
then 
命令序列1
else 
命令序列2
fi

2) bis flowchart branch if statement:

Shell Script applications (2)

3) Application Example double limb if statement:

[root@localhost ~]# vim b.sh
#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &>  /dev/null            //检查目标主机是否可以连通
if                                                                //关键字(如果)
[ $? -eq 0 ]                                        //测试上一条命令的返回结果
then                                                          //关键字(那么)
echo "Host $1 is up"
else                                                          //关键字(否则)
echo "Host $1 is down"
fi                                                              //关键字(结束)
#(注释)代码中,为了提高ping命令的测试率,使用“-c”表示只发送三个测试包;“-i”表示间隔时间为0.2秒;“-W”表示超时时间3秒。另外使用 “ &>  /dev/null”屏蔽ping命令执行过程的输出信息。
[root@localhost ~]# sh b.sh              
Host  is down                                         //执行脚本测试返回结果

3. multi-branch if statement

Since the if statement can be established according to the test results, the operation is not established, respectively, it is possible to nest, multiple determination.

1) multi-branch if statement syntax structure:

if  
条件测试操作1
then  
命令序列1
elif  
条件测试操作2 
then  
命令序列2
else
命令序列3
fi

2) multi-branch if statement Flowchart:

Shell Script applications (2)

3) Application example multi-branch if statement:

(1) Application Example (a)
[root@localhost ~]# vim c.sh
#!/bin/bash
read -p "请输入您的分数(0——100):" A
if
[ $A -ge 85 ] && [ $A -le 100 ]                       //85~100分,优秀
then
echo "$A分,优秀!"
elif
[ $A -ge 70 ] && [ $A -le 84 ]                        //70~84分,及格
then
echo "$A分,及格!"
else
echo "$A分,不及格!"                               //其他分数,不及格
fi
[root@localhost ~]# sh c.sh 
请输入您的分数(0——100):66
66分,不及格!
[root@localhost ~]# sh c.sh 
请输入您的分数(0——100):79
79分,及格!
[root@localhost ~]# sh c.sh 
请输入您的分数(0——100):99
99分,优秀!
//验证执行脚本效果
(2) Application Example (b)

Example requirements:
(1) using the extracted commands df root partition of disk usage, assigned to the variable DUG.
(2) Use mpstat command to extract the CPU usage (need to install sysstat package), assigned to the variable CUG.
(3) using the free command to extract the memory usage, assigned to the variable MUG.
(4) determining whether the monitoring project exceeded, you will need to save the alarm information to /tmp/alert.txt file.
(5) determining whether there /tmp/alert.txt file, as if there is an alarm message is sent.

[root@localhost ~]# vim 1.sh
#!/bin/bash
# 提取性能监控指标(磁盘占用、CPU使用、内存使用)
DUG=$(df -hT | grep "/$" | awk '{print $6}' | awk -F% '{print $1}')
CUG=$(expr 100 - $(mpstat | tail -1 | awk '{print $12}' | awk -F. '{print $1}'))
MUG=$(expr $(free | grep "Mem:" | awk '{print $3}') \* 100 / $(free | grep "Mem:" | awk '{print $2}'))
# 设置告警日志文件、告警邮箱
ALOG="/tmp/alert.txt"
AMAIL="root"
# 判断是否记录告警
if [ $DUG -ge 0 ]
then
echo "磁盘占用率:$DUG %" >> $ALOG
fi
if [ $CUG -ge 0 ]
then
echo "CPU使用率:$CUG %" >> $ALOG
fi
if [ $MUG -ge 0 ]
then
echo "内存使用率:$MUG %" >> $ALOG
fi
# 判断是否发送告警邮件,最后删除告警日志文件
if [ -f $ALOG ]
then
cat $ALOG | mail -s "Host Alert" $AMAIL
rm -rf $ALOG
fi
[root@localhost ~]# sh 1.sh 
[root@localhost ~]# mail                             //查看邮件
Heirloom Mail version 12.5 7/5/10.  Type ? for help.
"/var/spool/mail/root": 1 message 1 new
N  1 root                  Tue Jul 30 13:01  20/662   "Host Alert"
& 
……………………                     //省略部分内容
磁盘占用率:26 %
CPU使用率:1 %
内存使用率:18 %                                  //验证结果
#(注释)实验环境,大于等于0就发送邮件,实际生产环境视情况而定!

This can also view the message:


[root@localhost ~]# cat /var/spool/mail/root
……………                  //省略部分内容
磁盘占用率:26 %
CPU使用率:1 %
内存使用率:18 %

You have mail in / var / spool / mail / root in

Guess you like

Origin blog.51cto.com/14157628/2424803