Current location - Education and Training Encyclopedia - Graduation thesis - How to use Linux shell programming for system management and network management
How to use Linux shell programming for system management and network management
From the programmer's point of view, the Shell itself is a program written in C language. From the user's point of view, the Shell is the bridge between the user and the Linux operating system. Users can not only input commands to execute, but also use Shell script programming to complete more complex operations. With the improvement of Linux GUI, Shell programming still plays an important role in system management and other fields. A deep understanding and mastery of Shell programming is one of the compulsory courses for every Linux user.

There are many kinds of Linux Shells, among which Bourne Shell(/usr/bin/sh or /bin/sh), Bourne Again Shell(/bin/bash), C Shell(/usr/bin/csh), K Shell(/usr/bin/ksh) and Shell for Root(/sbin/sh) are common. Different Shell languages have different grammars, so they cannot be used interchangeably. Each kind of shell has its own characteristics. Basically, it is enough to master any one of them. This article focuses on Bash, which is also Bourne's Shell. Bash is widely used in daily work because it is easy to use and free. At the same time, Bash is also the default Shell of most Linux systems. In general, people don't distinguish between Bourne shell and Bourne shell, so in the following text, we can see #! /bin/sh, or change it to #! /bin/bash .

The format of Shell scripts written with a text editor (such as vi) is fixed, as shown below:

#! /bin/sh

# Comment

Your orders are here.

The symbol # in the first line! Tell the system that the program specified in the subsequent path is a Shell program that interprets this script file. If there is no such sentence in the first line, an error will occur when executing the script file. The following part is the main program. Like high-level languages, Shell scripts also have variable assignments and control statements. Except the first line, the line starting with # is a comment line until the end of this line. If a line is not finished, you can add ","at the end of the line to indicate that the next line and this line will be merged into the same line.

After editing, save the script as filename.sh, and the file name suffix sh indicates that this is a Bash script file. When executing a script, first change the properties of the script file to executable:

chmod +x filename.sh

The method of executing the script is:

. /filename.sh

Let's start with the classic hello world and look at the simplest Shell script.

#! /bin/sh

# Print hello world in the console window

a = "hello world "

echo $a

Shell script is a weakly typed language, and you don't need to declare its type before using variables. The new variable will be stored in the local data area. This variable belongs to the current Shell, and no child process can access this local variable. These variables are different from environment variables. Environment variables are stored in another memory area, called user environment area, and children can access the variables in this memory. Variable assignment method is:

Variable name = variable value

If you assign a value to a variable that already has a value, the new value will replace the old value. When you take a value, you should add $ before the variable name and $variable_name can be enclosed in quotation marks, which is obviously different from other high-level languages. If there is confusion, you can use curly braces to distinguish it, such as:

Respond to "hi, $ TERM as"

You won't output "Hi, hello worlds", but "Hi", because the Shell regards $as a variable, but $ as has no assignment and its value is empty. The correct method is:

Respond to "Hi, ${a}s"

Variables in single quotes will not be replaced.

About variables, you also need to know a few Linux commands related to them.

Env is used to display variables and their values in the user environment area; Set is used to display variables and their values in local data area and user environment area; Unset is used to delete the current value of the specified variable, which will be specified as NULL;; The export command is used to transfer variables in the local data area to the user environment area.

Let's look at a more complicated example. With this example, let's talk about the syntax of Shell scripts.

1 #! /bin/bash

2 # We have less than 3 parameters. Print help text:

3 if[$ #-lt 3]; then

4 cat<& lt help

5 ren-Rename multiple files using sed regular expressions.

six

7 usage: ren 'regexp' 'replacement' file

8 Example: Rename all *. HTM file in *. html:

9' HTM$' 'html' *. Suffix of html file

10

1 1 help

1exit 20

13 fi

14 OLD="$ 1 "

15 NEW="$2 "

16 # shift command deletes a parameter from the list.

17 # command line parameter.

18 flights

19 flights

20 # $* contains all the files now:

The file in $ * is 21; do

22 if[-f " $ file "]; then

23 NEW file = ` echo " $ file " | sed " s/$ { OLD }/$ { NEW }/g " ` 1

24 if[-f " $ new file "]; then

25 echo "Error: $newfile already exists"

The other 26

27 echo "Rename file to newfile"

28 mv "$file" "$newfile "

29 fi

30 Philippine dollars

3 1 complete

Let's take a look at it from the beginning. As explained in the last example in the first two lines, there is something new starting from the third line. If statement is a flow control statement like other programming languages. Its syntax is:

If ...; then

elif…; then

other

The ship does not bear the loading fee.

Unlike other languages, the conditional part of the if statement in a Shell script should be separated by semicolons. [] in the third line represents a conditional test. Common condition tests are as follows:

[-f "$file"] Judge whether $file is a file.

[$a -lt 3] Judge whether the value of $a is less than 3. Similarly, -gt and -le respectively represent greater than or less than or equal to.

[-x "$file"] Judge whether the $file exists and whether it has executable authority. Similarly, -r tests the readability of the file.

[-n "$a"] Judge whether the variable $a has a value, and use -z to test the empty string.

["$a" = "$b"] Judge whether the values of $a and $b are equal.

[cond 1 -a cond2] Judge whether cond 1 and cond2 are both true, and -o indicates that cond 1 and cond2 are both true.

Note the spaces in the conditional test section. There are spaces on both sides of square brackets, and there are spaces on both sides of symbols such as -f, -lt and =. Without these spaces, the Shell will make an error when interpreting the script.

$ # indicates the number of command line parameters, including $0. In the Shell, the script name itself is $0, and the rest are $0, $ 1, $2…, ${ 10}, $ {1} and so on. $ * indicates the whole parameter list, excluding $0, that is, the parameter list excluding the file name.

Now we understand that the third line means that if there are fewer than three parameters in the script file, the content between the if and fi statements will be executed. Then, the content from the fourth line to the eleventh line is called Here document in Shell scripting, and Here document is used to pass multiple lines of text to a command. The format of Here document is

The exit in the twelfth line is a command of Linux, which means to exit the current process. All Lexitux commands can be used in Shell scripts. On the one hand, clever use of Linux commands can also greatly reduce the length of Shell scripts.

Fourteen sentences and fifteen sentences are assignment statements, which assign the first and second parameters to the variables OLD and NEW respectively. The following two sentences are comments. Note The function of the following two shift is to delete the first and second parameters in the parameter list, and the following parameters will become the new first and second parameters in turn. Note that the parameter list does not initially contain $0.

Then, from line 2 1 to line 3 1 is a loop statement. The loop in the Shell script has the following format:

while[cond 1]& amp; & amp{ | | }[cond 2]…; do

finished

Do for var in …

finished

for((cond 1; cond2cond3 )) do

finished

Until [cond1] & & amp{ | | }[cond 2]…; do

finished

In the above loop, you can also use break and continue statements similar to those in C language to interrupt the current loop operation. The loop in line 2 1 is to put the parameters in the parameter table into the variable file one by one. Then enter the loop to judge whether the file is a file. If it is a file, search and generate a new file name with sed command. Sed can basically be regarded as a search and replace program, which reads text from standard input (such as pipes) and outputs the results to standard output. Sed uses regular expressions to search. Line 23, the function of the anti-tick (`) is to take the command between two anti-ticks and output the result, here is to take the result and assign it to the variable newfile. After that, it is judged whether the new file already exists, otherwise, the file is changed to a new file. In this way, we can understand the role of this script. Other scripts written by Shell Script are similar to this, but the syntax and usage are slightly different.

Through this example, we understand the writing rules of Shell scripts, but there are still a few things to say.

First, in addition to the if statement, there is a case statement in the Shell script that is similar to the multi-branch structure in C language, and its syntax is:

Case change

Mode 1)

… ; ;

Mode 2)

… ; ;

*)

… ; ;

Environmental systems applications center environmental systems applications center

Let's take another example to see the usage of the case statement.

while getopts vc: OPTION

do

The case $ option is in the

C) copy =$OPTARG

ehco " $ COPIES;

V) Echoing "Su Yang"; ;

\? ) exit1; ;

Environmental systems applications center environmental systems applications center

finished

The getopts above is similar to the function getopts provided by C language. In Shell scripts, getopts is usually used in combination with the while statement. The syntax of getopts is as follows:

Getopts option _ string variable

Option_string contains a single-character option string. If getopts finds a hyphen in the command line argument, it compares the character after the hyphen with option_string. If the match is successful, set the value of the variable to this option. If not, set the value of the variable to? . Sometimes, the option takes a value, such as -c5. At this point, you should add a colon after the option letter in option_string. When getopts finds the colon, it will read the value and put it in the special variable OPTARG. This order is very complicated. If necessary, readers can refer to the relevant materials written by the shell in detail.

The function of the above loop is to take out the options after the script name in turn. If you entered an illegal option, please enter "? Specify the section and exit the script.

Secondly, Bash provides an extended choice for interactive applications, and users can choose from a set of different values. Its syntax is as follows:

Choose var to do in …

Break;

finished

For example, the output of the following program is:

#! /bin/bash

Echo "Your choice?"

Select var in "a", "b" and "c"

break

finished

echo $var

-

Your choice?

1) a

2) b

3) c

Third, user-defined functions can also be used in Shell scripts. The syntax is as follows:

Function name ()

{

}

For example, we can put the fourth to twelfth lines in the second example above into a function body called help, and then write help directly every time we call it. The processing method of function call parameters in the function is to directly use the aforementioned $ 1 and $2 to represent the first and second parameters respectively, and use $ * to represent the parameter list.

Fourthly, we can debug Shell scripts under the shell. Of course, the easiest way is to use the echo output to check the variable value. Bash also provides a real debugging method, which is to use the -x parameter when executing scripts.

Shh? X file name.sh

This will execute the script and display the values of all variables in the script, or you can use the parameter -n, which does not execute the script and only returns all syntax errors.