Basic operation of linux (write shell script)

If the picture in the article hangs up again, please go to the official account to check 

Finally, I have come to the chapter of shell scripting. I have sold a lot of articles in the past to talk about how shell scripts are important. It is true that shell scripts are very important in the operation and maintenance of Linux system administrators. The following author will take you to officially enter the world of shell scripting.

So far, do you understand what a shell script is? If you understand it best, it doesn't matter if you don't understand, I believe that as you deepen your study, you will become more and more aware of what a shell script is. First of all, it is a script and cannot be used as a formal programming language. Because it runs in the Linux shell, it is called a shell script. To put it bluntly, a shell script is a collection of commands. For example, I want to achieve this operation: 1) enter the /tmp/ directory; 2) list all file names in the current directory; 3) copy all current files to the /root/ directory; 4) delete All files in the current directory. The simple 4 steps requires you to type the command 4 times in the shell window and press Enter 4 times. Is this troublesome? Of course these 4 steps are very simple, what if it is a more complex command setting that requires dozens of operations? It would be troublesome to type on the keyboard one at a time. So you might as well record all the operations in a document, and then call the commands in the document, so that the operation can be completed in one step. In fact, this document is a shell script, but this shell script has its special format.

Shell scripts can help us to manage the server very conveniently, because we can specify a task plan to execute a certain shell script to meet our needs. This is a very proud thing for Linux system administrators. The current 139 mailbox is very easy to use. When sending emails, you can also send an email notification SMS to the user. Using this, we can deploy a monitoring shell script on our Linux server, such as the network card traffic is abnormal or the server When the web server is stopped, you can send an email to the administrator, and at the same time send an alarm message to the administrator so that we can know that there is a problem with the server in time.

There is a problem that needs to be agreed. All custom scripts are recommended to be placed in the /usr/local/sbin/ directory. The purpose of this is to better manage the documents; secondly, the administrator who takes over you in the future will know Where to put custom scripts for easy maintenance.

[ The basic structure of shell scripts and how to execute them ]

 

 

Shell scripts usually have a suffix of .sh. This does not mean that the script cannot be executed without the .sh, it is just a habit of everyone. So, if you find a file with a suffix of .sh in the future, it must be a shell script. The first line in test.sh must be "#! /bin/bash", which means that the file uses bash syntax. If this line is not set, then your shell script cannot be executed. '#' means a comment, as mentioned earlier. Followed by some related comments of the script, as well as the author, creation date or version, and so on. Of course, these comments are not necessary. If you are lazy, you can omit them, but the author does not recommend omitting them. Because as your working hours increase, you will write more and more shell scripts. If one day you look back at a script you wrote, you may forget what the script is for and when you wrote it. of. So it is necessary to write a comment. In addition, you are not the system administrator. If another administrator views your script, wouldn’t it be very depressing if he doesn’t understand it. Below the script is the command to be run.

The execution of the shell script is very simple, just "sh filename" directly, and you can also execute it like this

 

 

By default, the document we edit with vim does not have execution permission, so you need to add an execution permission so that you can directly use'./filename' to execute this script. In addition, when using the sh command to execute a shell script, you can add the -x option to view the execution process of the script, which will help us debug where the script is wrong.

 

 

The command'date' is used in this shell script, and its function is to print the current system time. In fact, the date usage rate in shell scripts is very high. There are several options that I often use in shell scripts:

 

 

%Y means year, %m means month, %d means date, %H means hour, %M means minute, %S means second

 

 

Note the difference between %y and %Y.

 

 

 

 

The -d option is also frequently used, it can print the date n days ago or n days later, of course, it can also print the date n months/years ago or later.

 

 

In addition, the day of the week is also commonly used

 

 

[ Variables in shell scripts ]

The use of variables in shell scripts makes our scripts more professional and more like a language. Just kidding, the role of variables is of course not for professionalism. If you write a 1000-line shell script, and a certain command or path appears hundreds of times in the script. Suddenly you feel that the path is wrong and want to change it. Wouldn't it be necessary to change it hundreds of times? Although you can use the batch replacement command, it is also very troublesome, and the script seems a lot bloated. The role of variables is used to solve this problem.

 

 

Backticks are used in test2.sh, do you remember its function? 'd' and'd1' appear as variables in the script, and the format of the definition of the variable is "variable name=variable value". When quoting variables in the script, you need to add the'$' symbol, which is consistent with the custom variables in the shell mentioned earlier. Let's take a look at the results of the script execution.

 

 

Below we use the shell to calculate the sum of two numbers.

 

 

Mathematical calculations should be enclosed in'[ ]'and a'$' should be attached to the outside. The script result is:

 

 

Shell scripts can also interact with users.

 

 

This uses the read command, which can get the value of the variable from the standard input, followed by the variable name. "Read x" means that the value of the x variable needs to be entered by the user through the keyboard. The script execution process is as follows:

 

 

We might as well add the -x option to take a look at this execution process:

There is a more concise way in test4.sh.

 

 

The read -p option is similar to echo. The execution is as follows:

 

 

Have you ever used such a command "/etc/init.d/iptables restart" The /etc/init.d/iptables file in front is actually a shell script, why can it be followed by a "restart"? Here is the shell The preset variables of the script. In fact, the shell script can be followed by variables when it is executed, and it can also be followed by multiple variables. May as well as the author write a script, you will understand.

 

 

The execution process is as follows:

 

 

In the script, would you be wondering where the $1 and $2 come from, which are actually the default variables of the shell script, where the value of $1 is the value 1 entered during execution, and the value of $2 is the value entered during execution $2, of course, there is no limit to the default variables of a shell script, this time you understand. There is also a $0, but it represents the name of the script itself. May wish to modify the script.

 

 

You must have guessed the result of the execution.

 

 

[ Logical judgment in shell script ]

If you have studied C or other languages, I believe you will not be unfamiliar with if. We can also use if logic to judge in shell scripts. The basic syntax of if judgment in the shell is:

1 ) Without else

if judgment statement; then

command

be

 

 

The form ((a<60)) appears in if1.sh. This is a unique format in shell scripts. If you use a parenthesis or don't use it, you will get an error. Please remember this format. The execution result is

 

 

2 ) With else

if judgment statement; then

command

else

command

be

 

 

The results of the implementation are:

 

 

3 ) With elif

if judgment statement one; then

command

elif judgment sentence two; then

command

else

command

be

 

 

Here && means "and", of course you can also use || to mean "or", the execution result:

 

 

The above is just a brief introduction to the structure of the if statement. In addition to the form of "(( ))", you can also use "[ ]" when judging the magnitude of the value. But you can’t use symbols like >, <, =, you need to use -lt (less than), -gt (greater than), -le (less than or equal to), -ge (greater than or equal to), -eq (equal to), -ne (not equal to).

 

 

Let's look at the use of && and || in if.

 

 

In shell scripts, if also often judges file attributes, such as judging whether it is a normal file or a directory, and judging whether the file has read-write execution permissions. There are also a few commonly used options:

-e: Determine whether the file or directory exists

-d: Determine whether it is a directory and whether it exists

-f: Determine whether it is a normal file and exists

-r: Determine whether the document has read permission

-w: Determine whether there is write permission

-x: Determine whether it is executable

When using if to judge, the specific format is: if [-e filename]; then

 

 

In shell scripts, in addition to using if to judge logic, there is also a common way, that is, case. The specific format is:

case variable in

value1)

command

;;

value2)

command

;;

value3)

command

;;

*)

command

;;

esac

In the above structure, there is no limit to the number of values, and * represents other values ​​besides the above value. Next, the author writes a script to determine whether the input value is odd or even.

 

 

The value of $a is either 1 or 0, the execution result is:

 

 

You can also look at the execution process:

The case script is often used to write startup scripts for system services. For example, it is used in /etc/init.d/iptables. You may wish to check it out.

[ Loop in shell script ]

Shell script can also be regarded as a simple programming language, of course, loops are indispensable. The commonly used loops are for loops and while loops. The structure of the two loops will be introduced separately below.

 

 

The seq 1 5 in the script represents a sequence from 1 to 5. You can run this command directly to try it. The script execution result is:

 

 

Through this script, you can see the basic structure of the for loop:

for variable name in loop condition; do

command

done

The condition part of the loop can also be written in this form, separated by spaces. You can also try, for i in `ls`; do echo $i; done and for i in `cat test.txt`; do echo $i; done

Let's take a look at this while loop again, the basic format is:

while 条件; do

command

done

The execution result of the script is:

 

 

In addition, you can ignore the loop condition. I often write monitoring scripts like this.

while :; do

command

done

 

 

 

 

[ Functions in shell scripts ]

If you have studied development, you must know the role of functions. If you are new to this concept, it doesn't matter, it's actually very easy to understand. The function is to organize a piece of code into a small unit, and give this small unit a name, when this code is used, it can directly call the name of the small unit. Sometimes a certain section of the script is always used repeatedly. If it is written as a function, it can be replaced by the function name every time it is used, which saves time and space.

 

 

The sum() in fun.sh is a custom function, which should be used in a shell script

function function name () {

command

}

Define functions in this format.

The execution process of the previous script is as follows:

 

 

One thing I want to remind you is that in shell scripts, functions must be written at the top, not in the middle or at the end, because the function is to be called. If it is called before it appears, it will definitely make an error.

Shell scripts are generally introduced so much. The examples given by the author are the most basic, so even if you have a complete grasp of all the examples, it does not mean how good your shell scripting ability is. So in the remaining days you should practice as much as possible and write more scripts. The more scripts you write, the stronger your ability will be. I hope you can find a book dedicated to shell scripting to study it in depth. Then the author will leave you a few practice questions for shell scripts, you'd better not be lazy.

1. Write a shell script to calculate the sum of 1-100;

2. Write a shell script that requires you to enter a number, and then calculate the sum from 1 to the number you entered. It is required that if the number you enter is less than 1, enter it again until you enter the correct number;

3. Write a shell script to copy all the directories (only one level) under the /root/ directory to the /tmp/ directory;

4. Write a shell script to create users user_00, user_01, …, user_100 in batches, and all users belong to the users group;

5. Write a shell script to intercept the first column of the line containing the keyword'abc' in the file test.log (assuming the delimiter is ":"), and then sort the intercepted numbers (assuming the first column is a number), Then print out the columns that are repeated more than 10 times;

6. Write a shell script to determine whether the entered IP is correct (the rule of IP is n1.n2.n3.n4, where 1<n1<255, 0<n2<255,="" 0<n3<255,=" "0<n4<255<="" span="">).

The following are the answers to the practice questions:

1. #! /bin/bash

sum=0

for i in `seq 1 100`; do

sum=$[$i+$sum]

done

echo $sum

2. #! /bin/bash

n=0

while [ $n -lt "1" ]; do

read -p "Please input a number, it must greater than "1":" n

done

sum=0

for i in `seq 1 $n`; do

sum=$[$i+$sum]

done

echo $sum

3. #! /bin/bash

for f in `ls /root/`; do

if [ -d $f ] ; then

cp -r $f /tmp/

be

done

4. #! /bin/bash

groupadd users

for i in `seq 0 9`; do

useradd -g users user_0$i

done

for j in `seq 10 100`; do

useradd -g users user_$j

done

5. #! /bin/bash

awk -F':' '$0~/abc/ {print $1}' test.log >/tmp/n.txt

sort -n n.txt |uniq -c |sort -n >/tmp/n2.txt

awk '$1>10 {print $2}' /tmp/n2.txt

6. #! /bin/bash

checkip() {

if echo $1 |egrep -q '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' ; then

a=`echo $1 | awk -F. '{print $1}'`

b=`echo $1 | awk -F. '{print $2}'`

c=`echo $1 | awk -F. '{print $3}'`

d=`echo $1 | awk -F. '{print $4}'`

for n in $a $b $c $d; do

if [ $n -ge 255 ] || [ $n -le 0 ]; then

echo "the number of the IP should less than 255 and greate than 0"

return 2

be

done

else

echo "The IP you input is something wrong, the format is like 192.168.100.1"

return 1

be

}

rs=1

while [ $rs -gt 0 ]; do

read -p "Please input the ip:" ip

checkip $ip

rs=`echo $?`

done

echo "The IP is right!"

Guess you like

Origin blog.csdn.net/h610443955/article/details/114536362