Shell script writing ideas and examples to explain _shell

Source: Internet
Author: User
Tags inode usage egrep
A brief introduction to shell script writing ideas and examples

Often heard around a lot of learning shell script Friends complain shell script is not easy to write, not difficult to write out the script has been an error, symbol space is too much, the wrong one can not run also difficult to troubleshoot.

Objectively speaking, the simplicity of the shell script is a bit of a worry, but in the Linux operation of the shell script used very widely, in some cases with the shell is very efficient, so shell scripting is one of the skills that must be mastered, we can not abandon. Main points of the method

To get back to the point, I'm going to share the experience I learned while writing a shell script and how to write a shell script.

1. Clear thinking: When we want to implement a function need to write a script is not to write, to avoid the need for what function to write a command to improve the first, this style often appear in the structure of difficult to adjust the problem. Before we start writing the script, it's important to figure out how to implement this function, including what commands and commands are in order.

2. The overall view: when we have the idea of the script, we can not immediately start writing, this time we need to think in mind each step of the possible situation, when there are various situations how to respond. It is possible in the shell script that we need to have multiple conditional judgments to implement a seemingly simple function, because the situation that appears on our current system is only one of many situations, and we have to implement a "global view" to make the script work correctly on any machine. Popular speaking is a process of eliminating bugs.

3. Forestall: As everyone regrets, the shell script has a lot of quotes parenthesis space, each meaning is not the same, more than a few white space meaning is not the same, write a dozens of-line shell script can write a one-time run without error or some difficulty. My study of shell script in the beginning of the force to develop a habit of myself, after every line to check a variety of symbol brackets, just start very slow, but write more speed faster and the error rate is getting lower and higher, when the habit of writing those symbols will become a habit not just beginning so painful.

4. Good memory is inferior to bad keyboard: there is a bad word, although not pleasant to hear, but can remind some are learning shell script friend say out also very good. How many lines of shell do you write when you complain about how hard the shell script is to write and how easy it is to go wrong? How many times have you hit the keyboard? When you practice countless times, you'll be able to say that after you've knocked the keyboard down. Right. You can say that, but it's not a complaint, it's an evaluation. Instance

Write script checkdisk.sh, run effect: Check disk partition space and inode usage, if more than 80%, broadcast warning space will be full

After you see the topic, you can read the questions first and then follow our methods.

The first step, we first to achieve the function to clear.

To see how disk partitions and Inode are used, the DF and Df-i commands are used.
The section that extracts the usage in the DF command uses grep for the cut, head and tail commands for text processing.
To compare values, you might want to use parentheses and numeric comparisons.
The final broadcast will use the Wall command.
Because disk partitions are not only one, you may also use if conditions and loops.

This time our thinking can be like this:
1. Use grep and other text processing commands to remove the percent value in DF
2. Use brackets to determine whether these values are greater than 80
3. The partition that corresponds to a value greater than 80 is broadcast with wall

The second step is to think about the problems and situations that will arise in each step and then respond.

In the last step we have cleared the line, now that the lines have been planned then start paving the way.

1. To remove the percent value in the DF command we first need to look at the percent value where the DF hit is occurring, then use the regular expression to match, then take out with the cut and so on, but there are many partitions and also to determine the use of the inode so we have to figure out how many partitions there are, So here are a few variables: variables that represent the number of disk space partitions, variables that represent the number of disk inode partitions, variables that represent the path of the partition being removed, and variables that represent the percentage of values taken out.

2. Because including inode, the disk partition to compare a lot, if one by one comparison will greatly increase the number of lines of the script, write very tired, here you can consider the use of the partition of the number of variables to compare the use of a circular statement of each partition to achieve more than 80% and output comparison results, And considering that there are inode can be judged by if elif.

3. Now that the road has been paved, let's get on the road.

Below I will post my script here, may seem to have some long, but in fact, as long as I read all of the above, it will feel very simple.

Note: Regular expressions that appear in the script I'm not going to go into the details if I want to get to know a friend and look it up in my last blog post. Script such as cut these commands specific features I do not speak carefully, interested friends can be online to check the relevant information.

#!/bin/bash #author:D river_c #mail: 740560896@qq.com #time: 2017-06-11 #filename: checkdisk.sh//above as annotation segment linenum= ' DF | Egrep "\<[[:d igit:]]{1,3}%.*" | Wc-l ' #将用正则表达式取到的磁盘分区个数赋值给linenum test1= ' df | Egrep-o "\<[[:d igit:]]{1,3}%.*" | Tr '% ' | Tr-s ' |sort-nr | head-n1 | Cut-d '-f1 ' #经过一系列的文本处理取出磁盘分区使用量最大的分区的数值赋给test1, this variable is the key to determining whether the cycle is going test2= ' df-i | Egrep-o "\<[[:d igit:]]{1,3}%.*" | Tr '% ' | Tr-s ' |sort-nr | head-n1 | Cut-d '-f1 ' #如同上一条命令, DF option More-I, the significance of the use of the largest number of the inode used in the partition of the value assigned to Test2, is also the key to the cycle of Num=1 #这个变量在整个判断过程中非常重要,

 This variable is used to determine the current action row in the while loop, to determine if 1 is added to implement the loop if ["$test 1"-ge "];then" #这个if的意义在于判断之前磁盘分区使用率最大的分区是否大于或等于80%, and to judge each partition in order of the execution loop While ["$num"-le "$linenum"] #这里就用到了上面的num和linenum变量, the meaning is to execute the following command when NUM is less than or equal to the number of disk partition rows, which is equivalent to having partition usage greater than 80% as long as the if is judged

 All partitions are compared in loops, because it is possible to use more than 80% and not just one partition. Do testnum1= ' DF | Egrep-o "\<[[:d igit:]]{1,3}%.*" | Tr '% ' | Tr-s ' |sort-nr | Head-n "$num" | tail-n1 | head-n1 | Cut-d '-f1 ' #这一段命令的功能是用于提取出分The value of the area usage is used for the subsequent comparisons, here notice my usage of the NUM variable in the command, and NUM needs to be brought in to the command in order to achieve the extraction testname1= ' df | Egrep-o "\<[[:d igit:]]{1,3}%.*" | Tr '% ' | Tr-s ' |sort-nr | Head-n "$num" | tail-n1 | head-n1 |  Cut-d '-f2 ' #这一段主要功能是提取分区路径, the significance is that the last line of command extracted from the value if more than 80%, when the broadcast disk partition is insufficient to give the end of which partition is nearly full ["$testnum 1"-ge "] && Wall "$testname 1" ' Will is full ' #这一段就是比较数值的和输出的部分, the command is very simple to understand, to note that the variable to see num=$[num+1] #当循环一次之后num加上1再次循环的时候就能匹配下一行的


The done Num=1 #num变量是否重新赋值为1直接决定了下面的判断是否能正常运行, because the value of NUM is 7 after the end of the loop above, and if you do not assign a value of 1, the following command is equivalent to not writing.
#这一部分的结构和上面是一样的, I will not explain every article, the main function of this section is to determine the amount of inode. elif ["$test 2"-ge ""] then while ["$num"-le "$linenum"] do testnum2= ' df-i | Egrep-o "\<[[:d igit:]]{1,3}%.*" | Tr '% ' | Tr-s ' |sort-nr | Head-n "$num" | tail-n1 | head-n1 | Cut-d '-f1 ' testname2= ' df-i | Egrep-o "\<[[:d igit:]]{1,3}%.*" | Tr '% ' | Tr-s ' |sort-nr | Head-n "$num" | tail-n1 | head-n1 | cut-d '-f2 ' ["$testnum 2"-ge ""] && Wall "$testname 2" ' Inode would be fulL ' num=$[num+1] do else echo "All filesystems are safe" #这里非常好理解, if the above does not have a match on the direct output of this piece of information.
Fi #养成好习惯 The end of the used variable is recycled. unset linenum unset test1 unset test2 unset num unset testnum1 unset testname1 unset testnum2 unset testname2 exit

Script content is the above section, in fact, according to my previous ideas, this script although the number of lines, but it is not difficult to understand, the script is not imagined so difficult, difficult is not to go hand. This topic is a good practice for beginners. Test

See here have friends will say, above splinters say so much in the end can not use to know after all, "Linux is interesting" we need to play to know.

Test system: CentOS 7.3 1611

[Root@centos7 ~]# DF
filesystem 1k-blocks Used Available use% mounted on
/dev/sda2      104806400 5397480  99408920   6%/
devtmpfs          485308       0    485308   0%/dev
tmpfs             499980       4    499976   1%/dev/shm
tmpfs             499980
7196             492784 2%/run Tmpfs 499980       0    499980   0%/sys/fs/cgroup/dev/sda3 52403200 32944 52370256   1%/ App
/dev/sda1        1038336  172116    866220 17%/boot tmpfs 100000       8     99992   1%/run/user/0
/dev/sr0         8086368 8086368         0 100%/run/media/root/centos 7 x86_64

You can see me because a disc is hung on the system, so there is a partition is 100%, run a script to test whether it can be measured.

[Root@centos7 ~]# checkdisk02.sh 

Broadcast message from root@centos7.com (pts/0) (Sun June 15:44:12 2017):

/run /media/root/centos is full

The partition name that is greater than 80% is rendered perfectly.

So now we're going to increase the partition usage to over 80% to see if it shows up.

[Root@centos7 ~]# dd if=/dev/zero of=/boot/file bs=1m count=800
#这里我们可以用dd命令在/boot directory to write a file/boot partition over 80%
800 +0 Records in
800+0 records out
838860800 bytes (839 MB) copied, 2.30907 s, 363 mb/sec
[Root@centos7 ~]# Checkdi sk02.sh 
#执行脚本
Broadcast message from root@centos7.com (pts/0) (Sun June 15:46:43 2017):

/run/media/root/ CentOS'll is full

broadcast message from root@centos7.com (pts/0) (Sun June 15:46:43 2017):/boot'll be

fu ll

When we put another partition in 80%, we still have a perfect presentation. The script works fine. Conclusion

In fact, in our learning process if encountered a feeling very difficult thing is not to say that their own intelligence limited limited, it is only to knock on the keyboard to find excuses, more knock more practice even if not understand also learn how to use.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.