WriteCode
Be preparedProgramAfter it becomes easier to learn what to do and how to use a program, a programmer must record his ideas and tell the computer what he wants. This is the so-called code to be used. Generally, organize your own thinking in the following order:
1. determine the tasks that the computer can perform.
2. determine the sequence of tasks executed by the computer
3. Select appropriate commands from the shell script language to execute those tasks.
4. Use the Linux text editor to edit a shell script and organize commands according to the task execution sequence.
Several programming terms
A single command sent to a computer is called command.
The code -- code
All commands that are organized together to complete a task are collectively referred to as programs-Program
Keywords retained by BASH Shell in Linux:
Case |
Elif |
Let |
Clear |
Else |
Read |
Continue |
If |
Then |
Echo |
For in |
While |
Variable
What is data?
The information obtained by the program from the prepayment becomes data-data. A good program follows the following three steps:
1. obtain data from hard disks or files
2. Perform some appropriate processing on the data
3. display the data on the screen and store it in a file.
String -- string
A string is a collection of multiple letters or characters. A character can be a hyphen or anything that can be found on the keyboard. A string may also consist of a single letter or character. A complete sentence may be a string. In fact, any combination of letters, spaces, and even numbers can be considered as a string.
Number -- number
A number can be composed of any number, such as money, age, height, and weight. A number can be either a negative number or a positive number, an integer, a fraction, or a decimal number. In the case of complexity, the number can also be a character. This double identity of data may be confusing, but it cannot cheat computers. If you tell a computer that it is an address or a part of a phone number, it treats the number as a letter or character. However, if a computer adds up a certain number, the computer treats it as a number rather than a character.
Understand what variables and values are
Computers know how to differentiate the data and strings entered by users, but it may be like "fan x soul x Tang ". For our readers, it is easy to regard 55-55-55 as the insurance number of a person, while the computer only treats it as a number or a string.
When the program uses the insurance number, it must also tell the computer: "It's time to use the insurance number. Where is it, right? It is placed in the variable named SSS"
The so-called variable is actually the place of a specific number of values (such as the insurance number) in a computer. The SSS insurance number lost to this variable name is a value.
Variable Classification
Linux uses the following two categories:
Local variables: these variables are created by a programmer and only used by the program designed by the programmer.
Environment variables: they are created by programmers or others, and can be used by both programmers and others.
Linux condition control statements
We are making decisions all our lives. For example, where do you want to travel to the United States, Japan, or France?
Decision is actually a wise choice. But we have to build them on the basis of certain conditions. If we have enough funds to travel? If the conditions are not true, even the most fascinating choice is just a fantasy.
Condition
A condition is a State that must exist or does not exist. If yes, the condition is true. Otherwise, the condition is false.
In Linux, conditions exist in the following two forms:
Ø Single Variable
A single expression
For example, put all the money into the wallet. Wallet is called a variable, and money in a wallet is called the value of a variable. Whether to go to hawaii depends on whether your wallet has enough money. If not, you cannot go. Therefore, the value of the wallet variable is zero, which means that there is not enough money to travel to Hawaii, and the condition is false.
For example, there is a lot of money in the wallet. But is the money enough for this trip? You have to ask yourself to see if the money in the wallet is greater than or equal to $1000 (the money needed for travel ). This is an expression that leads to either true or false results.
Conditions represented by Variables
The value of a variable is either true or false. This usually uses a non-zero representation of truth, and a zero representation of false. The following describes two methods to determine whether the value of a variable is true or false. The first method shows the value of the check variable, as shown in the following example:
If [$ haveenoughmoney-EQ 1]
The program uses the equal sign operator (-eq) to determine whether the value of the variable is true or false.
If you want to determine whether a condition is true, you can also let the program check whether the value of the variable is false, as shown below:
If [$ haveenoughmoney-Ne 0]
The non-equals operator (-ne) makes a judgment that is opposite to the logic. If the-EQ operator is used, the program checks whether the variable is true. On the contrary, if the-ne operator is used, the program checks whether the variable is false or not.
Conditions expressed by expressions
A condition can also be called an expression that requires the program to perform certain operations on information. For example, the program is required to check whether the value of a variable (such as your bank deposit, O (debit _ debit) O) is greater than a specific number. In this case, the results of an expression can only be true or false, and can only be one of them, as shown in the following example:
If [$ bankbalance-GT 3000]
-EQ |
Equal |
-GT |
Greater |
-Lt |
Less |
-Ne |
Not equal |
-Ge |
Greater than or equal |
-Le |
Less than or equal |
The program checks the value of the bankbalance variable to see if it is greater than 3000. This expression has only two possibilities: true or false. If the deposit is greater than 3000, it is true; if the deposit is less than 3000, it is false.
If statement
When you need to check whether a condition is true or false, you can use the if statement. The IF statement only tells the program: "If the condition is true, execute these commands. Otherwise, skip these commands ."
The IF syntax rules are as follows:
If {condition}
Then
Instrution
Fi
Generally, if a condition exists (that is, the condition is true), the program executes the instruction of the project.
The following two examples illustrate the use of the IF statement. The first example is to let the program determine whether a box is full, provided that the box can only hold up to 100 cookies.
If [$ quantity-EQ 100]
Then
Echo "the box is full"
Fi
This statement allows the program to check the value of the variable quantity to see if it is 100. If yes, it is displayed on the screen:
The box is full.
Otherwise, skip this statement and move it to the next statement of Fi. Note: Here, FI is a reserved word, which has a special meaning. (FI indicates the end of the IF Statement)
In another example, the program is required to check whether the box is full and whether there are other boxes available. If both conditions are true at the same time, the program will report that the cookie cannot be installed, as shown below:
If [$ quantity-EQ 100] & amp; {$ availableboxes-it 1}
Then
Echo "the box is full and you have no more boxes"
Fi
This statement requires the program to check the value of the variable quantity to see if it is 100, and whether the value of the variable availableboxes is smaller than 1. If both conditions are true, the information is displayed:
The box is full and you have no more boxes"
If the value of the quantity variable is not 100 and the numerator remains, the program skips this statement and moves it to the next statement of the reserved word fi.
If else statement
The IF statement allows the program to make a certain judgment by a condition. If the day is true, it executes a set of specified commands.
However, there is also a problem when using the if statement, that is, when the condition is false, another set of commands may need to be provided for the program. Of course, you can also use an if statement to solve this problem, that is, when the condition is false, let the program execute another set of commands. However, one method is simpler than this, which is the if else statement. The syntax rules of the IF else statement are as follows:
If [condition]
Then
Instruction1
Else
Instruction2
Fi
This statement indicates that if condition is true, the program executes the first group of commands (iinstruction1); If condition is false, the program executes the second group of commands (instruction2 ).
Now let's take a quiz to see if we know how to modify the following statements so that the program can display information on the screen:
The box is not full?
As follows:
If [$ quantity-EQ 100]
Then
Echo "the box is full"
Fi
You can use the following two methods to modify this statement, depending on how we express the condition. If you want to keep the conditions unchanged, you can modify them as follows:
If [$ quantity-EQ 100]
Then
Echo "the box is full"
Else
Echo "the box is not full"
However, you can also use the condition $ quantity-ne 100 to modify it, for example:
If [$ qurantity-ne 100]
Then
Echo "the box is not full"
Else
Echo "the box is full"
Fi
If else statement
Worried! If the condition is false, the program will unconditionally execute the second group of commands. Sometimes, we don't want this. Instead, you want the program to make another judgment before executing the second group of commands.
To achieve the above purpose, you can use the if Elif statement to let the computer make another judgment. It seems a little confusing, but it is quite easy to understand after getting used to it. The syntax rules of the IF Elif statement are as follows:
If [condition1]
Then
Instruction1
Elif
Instruction2
Fi
In this statement, if condition 1 is true, the program executes the first group of commands instruction1; otherwise, the program judges whether condition 2 is true. If the condition is not true, the program executes the second command instruction2; if condition 2 is false, the second command is skipped.
No matter when the if statement is used, the program executes at least one set of commands. However, if the if Elif statement is used, the program may skip these two sets of commands, as shown in the following example:
If [$ quantity-EQ 100]
Then
Echo "the box is full"
Elif [$ quantity-EQ 95]
Then
Echo "you can add 5 cookies to the box"
Fi
So what happens when the quantity value is 95? First, the program judges the value of the first conditional expression and finds that the value of the expression $ quantity-EQ 100 is false.
Then, the program determines the value of the second conditional expression and finds that the expression $ quantity-EQ 95 is true. Therefore, the program will display:
You can add 5 cookies to the box
However, when the quantity value is 94, what will happen?
As mentioned above, the program first checks the first conditional expression $ quantity-EQ 100 and determines that the value of this expression is false, so the program ignores the first group of commands. Then, the program detects the second condition expression quantity-EQ 95 and finds that it is false, so the second group of commands is ignored.
At this time, the Program reaches the end of the IF else statement body. Since no condition is true, the program does not execute any commands.
Multiple options using the if else statement
In a program, multiple if Elif statements are used for condition detection. The program can process multiple possibilities. The structure rules of multiple if Elif statements are as follows:
If [condition1]
Then
Instruction1
Elif [condition2]
Then
Instruction2
Elif [condition3]
Then
Instruction3
Fi
In this statement, if condition1 is true, the program executes the first group of commands instruction1; otherwise, it checks whether condition 2 is true. If condition 2 is true, run the second group of commands instruction2; otherwise, check whether Condition 3 is true. If Condition 3 is true, the third group of commands instruction3 is executed; otherwise, the third group of commands instruction3 is skipped.
Note: In a program, the more nested if Elif statements, the more dazzled it.
Ensure that Linux executes at least one set of commands
Imagine that if we write an if Elif statement with a huge result, we find that it cannot do anything. What does it feel like? O (partition _ tables) O Haha ~, This happens in actual programming. However, if an Elif fi statement is sent at the end of the IF Elif statement, this "disaster" can be avoided, as shown in the following example:
If [condition1]
Then
Instruction1
Elif
Instruction2
Elif
Then
Instruction3
Elif
Instruction4
Fi
In this statement, if condition1 is true, the program executes the first group of commands instruction1; otherwise, it checks whether condition2 is true. If condition 2 is true, run the second group of commands instruction2; otherwise, check whether Condition 3 is true. If Condition 3 is true, the third group of commands is instruction3; otherwise, the fourth group of commands is instruction4.
Case statement
Have you ever met this situation and asked the computer to make a decision in the case of many possibilities? For example, Let Computers make a special service for each of the company's five offices. To complete this task, the program may use a large number of if Elif statements, as shown below:
If [$ region-EQ "1"]
Then
Echo "Hello, Bob"
Elif [$ region-EQ "2"]
Then
Echo "Hello, Mary"
Elif [$ region-EQ "3"]
Then
Echo "Hello, Joan"
Elif [$ region-EQ "4"]
Then
Echo "Hello, Mike"
Elif [$ region-EQ "5"]
Then
Echo "Hello, Tom"
Fi
This program may be a bit difficult to read-although it is easy to read by computers. However, let's think about how it would be if the Office was increased to 20 and 20 if statements were processed!
Case statement
Suppose you want to design such a program to display different information for each office user program. Of course, readers can design this program as they said at the beginning: assign a number to each office and each number corresponds to a special message.
The function of the case statement is to compare the value on the right of the reserved word case with the value on the left of the closed brackets ")". The syntax rules are as follows:
Case variablename in
Value1)
Instruction
;;
Value2)
Instruction
;;
Esac
It can be seen from the above that the case statement starts with the reserved word case and ends with esac. It first checks the value of the variable variablename. If it is equal to value1, it executes the first set of instruction sets. If it is equal to value2, it executes the second set of instruction sets, and so on. At the same time, use two semicolons (;) at the end of each set of instruction sets (;;).
Case $ region in
1)
Echo "Hello, Bob"
;;
2)
Echo "Hello, Mary"
;;
3)
Echo "Hello, Joan"
;;
4)
Echo "Hello, Mike"
;;
5)
Echo "Hello, Tom"
;;
Esac
This code is easy to read because it removes the repeated Elif. Of course, you can add more possible values as long as you actually need them. In fact, the case statement makes the program much easier to understand like a pipeline.
However, when using the case statement, you must remember the following points:
The value to be matched by the program must contain one or more characters.
A variable or value can be used as the value to be matched by the program.
The right side of a variable or value must end with a closed bracket ")"
Default condition in case statement
In the case statement, if the user does not provide the required matching value to the program, the program cannot find the object to be matched. If it is the matching value required by the program design self-supplied program, this sometimes does not happen. However, if someone else provides it, the problem may come.
Suppose another office is added, and we have no time to update the program so that it can handle this new office. At this time, the program will ignore the new office because it cannot find any matching value.
However, we can use reserved characters (*) to leave a path for this purpose, that is, to provide a default situation for the program to perform some necessary operations here. See the following example:
Case $ region in
1)
Echo "Hello, Bob"
;;
2)
Echo "Hello, Mary"
;;
3)
Echo "Hello, Joan"
;;
4)
Echo "Hello, Mike"
;;
5)
Echo "Hello, Tom"
;;
*)
Echo "Sorry, your region is not on my list"
Esac
This code. If the value of $ office is equal to the number of an office, it displays an appropriate greeting. If the case statement does not match the value of $ office, execute the last command to display the information:
Sorry, your region is not on my list
Multi-layer nested Control Structure
Have you ever received a gift in a big box? When you open it quickly, there is a slightly smaller box in it. Open the small box and find another small box ...... Until you find the present.
In the programming process, the box contains the box phenomenon called nested ). If multiple if statements or case statements are combined, they are nested.
If nested Structure
Generally, an if statement must contain one or more commands, as shown in the following example:
If [$ office-EQ "1"]
Then
Echo "Hello, Bob"
Else
Echo "Sorry, your region is not on my first"
Fi
Next, replace the if statement with the case statement to overwrite the previous example:
Case $ office in
"1 ")
Echo "Hello, Bob"
;;
*)
Echo "Sorry, your region is not on my list"
Esac
Of course, you can also place other IF and case statements instead of a large number of commands in the IF or case statements. The following is an example of using the if statement:
If [$ office-EQ "1"]
Then
If [$ regionalmgr-EQ "Bob"]
Then
Echo "Hello, Bob"
Fi
This program first checks the value of the variable $ office. If it is 1, check the value of the variable $ regionalmgr. If the value is Bob, the welcome greeting is displayed.
Case nested Structure
The case statement can also be nested (the same as the method in the previous example). See the following example:
Case $ office in
"1 ")
Case $ regionalmgr in
"Bob ")
Echo "Hello, Bob"
;;
Esac
;;
Esac
While Loop
While loop execution process, if the people standing under the eaves shelter, often need to check whether the rain is still the same. If the rain is still there, they will have to stay, or else they will be able to drive. Here, rain is a condition that determines whether they can go.
We can also write a program that allows users to answer a question until the answer is correct before continuing to run the program. If the user does not answer the question once, the program checks it once to see if it is the same as the correct answer. This check is similar to a person standing under the eaves watching whether the sky is still raining. If the program finds that the user's answer is incorrect, it will tell him that the answer is incorrect and return to the top of the while loop, waiting for the next answer.
The general format of the while loop is as follows:
While [condition]
Do
Instruction
Done
Next, we will learn the usage of the while loop so that the program executes some commands only when a specific condition is met-for example, if the answer entered by the user from the keyboard is correct.
In a while loop, a variable or expression with the inverted result true or false must be put, while in the while loop body, any number of commands can be put.
Are you sure you want to use the while loop?
When writing a program, we generally list all the commands that the computer needs to run. Some of the commands must be executed multiple times. In this case, commands are not rewritten, but placed in a loop called while.
If you need to execute a group of commands repeatedly and the condition is true, you can use the while loop. For example, if you design a program that prompts the user to enter the password, you can put those commands into a while loop until the user enters the correct password to terminate the repeated operation.
However, if you do not want the program to repeatedly execute some commands, do not use a while loop. For example, when a user encounters a program error, we always want the computer to display the unified error information on the screen. The command that clearly shows the error information is repeatedly executed in the program, but the command will be executed only when the error occurs. If these commands are put into a while loop, the program will continuously display the information. The best way to solve this problem is to put these commands into a sub-program. The program calls this subprogram only when the information needs to be displayed.
Use of while loop in Linux code
When the program encounters a while loop, it first checks its condition and asks "is this thing true or false ?" The program reads the commands in the while loop body only when the condition is true.
See the following example of a while loop:
Declare raining = "1"
While ["$ raining"-EQ "1"]
Do
Echo "still raining"
Done
The commands in this while loop are described as follows:
Declare declares to create a string variable named raining and assign it to 1. The surface of this value is a true value.
The while keyword indicates whether the value of $ raining is still 1. If yes, it means the rain is still down. If the rain is still down, ECHO Displays the information still raining on the screen.
Done is the end of the while loop.
Of course, to make this program a little practical, you also need to add some instructions in this example. For example, in the above example, because the value of $ raining never changes, the program always displays this information. Remind readers that the above program is an endless loop, so the while loop conditions are always true.
To avoid endless loops, you need to add some instructions in the program to check whether the rain is still down. For example, set some commands in the while loop to set the value of $ raining to 0 when the rain stops.
For in Loop
Suppose you have won the grand prize and want to write a letter to invite your friends to a celebration. You may write a program to print these letters, but you will find that the program is not running once. You must enter the name of a friend.
If the for in loop is used, this type of problem can be avoided. Because the for in loop allows you to store the names of all your friends in a list, and then let the program print these invitations with the name of each person. This is similar to mail merge. Therefore, when you want a program to execute a series of commands when the condition is true, it is to use a while loop. It will always run until the program has a command condition modified to false to terminate.
However, if you know the specific number of times the command is executed in the loop body, you can use the for in loop for a long time.
The general format of the For in loop is as follows:
For variablename in wordlist
Do
Instruction
Done
Wordlist is a list of string values that will be assigned to the variable (variablename. This variable can be used by the commands in the loop body.
How many commands are placed in the loop body depends on the actual needs of the program. The biggest challenge you encounter is whether you have mastered the program commands.
Whether to use the for in Loop
There is no rule to indicate when to use the for in loop, which requires your own analysis.
However, the for in loop is often used in the following two cases:
Perform the same operation on multiple character values
Use the string value series in a certain order
For example, if you use a program to add salaries to five employees, follow these steps:
1. Find the salary of an employee in the payroll
2. Calculate New salary
3. Save the new salary to the payroll
You can first place the name of each employee in a list associated with the for in loop. Then, let the program look for their records, perform some necessary mathematical operations, and record them into the salary file according to the employee's name order.
How to Use the for in Loop
If you want to show off your new programming knowledge in front of your friends, you may wish to write a program to show their greetings when they gather in front of the computer. There are many different methods to write this program.
Take a look at the following example:
Echo "Hello, Mary"
Echo "Hello, Joe"
Echo "Hello, Sue"
This program only repeats the same command three times and changes its name.
Use another method to rewrite the above example. See:
Let counter = 1
While ["$ counter"-it 5]
Do
If ["$ counter"-EQ 1]
Then
Echo "Hello, Mary"
Fi
If ["$ counter"-EQ 2]
Then
Echo "Hello, Joe"
Fi
If ["$ counter"-EQ 3]
Then
Echo "Hello, Sue"
Fi
Done
The preceding commands are described as follows:
Every time a command in a while loop is executed, the computer checks the counter value once.
Display the welcome information for a person depends on the counter value.
The last command in the while loop body (let counter = $ counter + 1) is to add 1 to the value of $ counter and assign the new value to counter. This command allows the computer to display information about everyone.
After all these commands are executed, the computer checks the counter value to see if it is less than 5. If it is less than 5, it is executed once. If it is greater than 5 or equal to 5, the loop is aborted.
The previous program shared 16 lines of code. Let's look at the example of using the for in loop below. It only uses 3 lines and gets the same result.
Please refer to the example written in the for in loop below:
For friend in Mary Joe Sue
Do
Echo "Hello, $ friend"
Done
In the first line of the For in loop, the name of three people is followed by the name of for friend in. In this way, a word table is created, and these names can be assigned to the variable friend as values.
Note that there is a space between $ friend and period. If this space is not left, the program will follow the friend. (With periods) instead of friend (without periods) to find variables.
The running process of this program is as follows:
1. The computer extracts the first value from the word table and assigns it to the variable friend.
2. Then, the computer displays the welcome word on the screen.
3. Return the result from the computer, and then assign the second value to friend.
This program runs until the values in the Word Table are used up, that is, after greeting everyone, the for in loop is aborted.
Therefore, through the use of the For in loop, you can reduce the program code written with the while loop from 16 lines to 3 lines, and the program is easier to read.
Use Word Table
The values assigned to a variable are collectively referred to as wordlist ). It is a list of string values (combinations of characters and numbers). We can assign a value to the variable at a time in order.
Note the following about word lists:
The value assigned to a word table must be a string value.
All values must be separated by spaces.
If spaces are also part of a string, quotation marks must be placed on both sides of the string.
To illustrate the usage of a string containing spaces, see the following example:
For friend in "Mary" "Joe" "sue"
Do
Echo "Hello, $ friend"
Done
Loop nesting and quick exit
Do you remember when my mom asked you to clean toys? After complaining for a while, you have to grab the toys and stuff them into the boxes. You repeat this action over and over again. Because every toy is made up of many blocks, you need to put the blocks in your own boxes before you put them in the toy box.
In this example, taking a toy is equivalent to an outer loop, and taking a block is equivalent to an indside loop ). Embedding another loop in one loop forms a general Loop Series, called a nested loop ). The use of nested loops makes it easier to organize programs, even though it is difficult to read them.
Use nested loops
Nested loops indicate that each execution of an outer layer is illusory and needs to be executed multiple times. See the following example of a nested loop:
Let flag = 1
While ["$ flah"-lt 4]
Do
For friend in Bob Mary Sue
Echo "Hello, $ friend"
Done
Let flag = "$ flag + 1"
All in all, information about Bob, Mary, and Sue is displayed on the screen three times. This program contains two loops: a while loop and a for in loop. The while loop (outer loop) repeats three times in total, while the inner loop is the for in loop of the nested loop. In the while loop, the greetings to everyone are unrealistic.
The commands of the program are described as follows:
Let flag = 1 defines a numeric variable and assigns it a value of 1.
While ["$ flag"-lt 4] detects the value of $ flag. If its value is 1, the program executes the commands in the while loop body.
For friend in Bob Mary Sue is the starting part of a nested loop. It assigns every value in the Word Table (Bob Mary Sue) to the variable friend.
Echo "Hello, $ friend" shows greetings for the value of the welcome variable $ friend
The first done indicates that it is the end of the For in loop.
Let flag = "$ flag + 1" indicates adding 1 to the variable $ flag and re-assigning it to the variable flag.
The second done indicates the end of The while loop.