Shell Programming Summary

Source: Internet
Author: User
Tags arithmetic logical operators

First, the basics of learning Shell scripts

" Special symbols in theLinux shell "

1. * : Represents 0 or more characters or numbers.

Test can have no characters, or multiple characters, or it can be matched.

2.? : represents only one arbitrary character

Whether it is a number or a letter, as long as it can be matched.

3. # : This symbol in Linux indicates the meaning of the comment description, that is, "#" after the content of Linux ignored.

Insert "#" at the beginning or middle of the command, and Linux will ignore it. This symbol is used in a lot of shell scripts.

4. WC : Count the number of lines, characters, and words of a document, and the commonly used options are:

-L: Count rows

-M: Statistics of characters

-W: Number of statistical words

5. >>, 2>, 2>> : The above-mentioned directional symbols > and >> denote the meaning of substitution and addition, then there are two symbols which are 2> and 2> here. > respectively for error redirection and error append redirection, when we run a command error, the error message will be output to the current screen, if you want to redirect to a text, then use 2> or 2>>.

6. [] : brackets, the middle is a combination of characters, representing any one of the intermediate characters

7. && | |

A semicolon has just been mentioned above for the delimiter between multiple commands. There are also two special symbols that can be used in the middle of multiple commands: "&&" and "| |". Here are a list of the following:

1) Command1; Command2

2) Command1 && Command2

3) Command1 | | Command2

Use ";" , the Command2 is executed regardless of whether the Command1 executes successfully, and when "&&" is used, only command2 executes after Command1 execution succeeds, otherwise command2 does not execute; use "| |" , Command1 execution succeeds Command2 not execute, otherwise go to execute Command2, in short Command1 and Command2 always have a command to execute.

8.test Test Command

The test command is used to check if a condition is true, and it can test three aspects of a value, string, and file with the following characters:

(1) Numerical test:

-eq: Equals is True
-ne: Not equal to True
-GT: Greater than true
-ge: greater than or equal to true
-lt: Less than true
-le: Less than or equal to true

(2) String test:

=: Equals is True
! =: Unequal is true
-Z String: String length pseudo is True
-N String: The string length is false and true

(3) file test:

-e File name: True if the file exists
-r file Name: True if the file exists and is readable
-W file name: True if the file exists and is writable
-X File Name: True if the file exists and is executable
-S file name: True if the file exists and has at least one character
-D file Name: True if file exists and is directory
-F file Name: True if the file exists and is a normal file
-C file Name: True if the file exists and is a character-specific file
-B file Name: True if the file exists and is a block special file

In addition, Linux also offers a ("! "), or ("-O ", Non ("-a ") three logical operators are used to connect test conditions with the priority of:"! "Highest,"-a "followed by,"-O "lowest.

Also, bash (SH cannot run ) can perform simple arithmetic operations in the following format:

$[expression]
Example: var1=2
VAR2=$[VAR1*10+1]
Then: The value of VAR2 is 21.

SH can run the following:

$ ((expression))
Example: var1=2
VAR2=$[VAR1*10+1]
Then: The value of VAR2 is 21.

[] is actually shorthand for the test command in bash. That is, all of [expr] equals test expr, Note that there are spaces .

9. (())

How to use:

Grammar:

(expression 1, expression 2 ... ))

Characteristics:

1, in the double bracket structure, all expressions can be like C language, such as: a++,b--, etc.

2. In a double-brace structure, all variables may not be added: "$" symbol prefix.

3, the double parenthesis can carry on the logical operation, arithmetic

4. Double bracket structure expands the FOR,WHILE,IF condition test operation

5, support multiple expression operation, between each expression with "," separate

Usage examples:

    • Extended arithmetic
1234567891011 #!/bin/sha=1;b=2;c=3; ((a=a+1));echo $a; a=$((a+1,b++,c++));echo$a,$b,$c

Operation Result:

SH testsh.sh
2
3,3,4

Multiple expressions are supported between the two-parenthesis structure, which is then supported by common C-language operators such as subtraction. If the double parenthesis Band: $, the expression value is obtained and assigned to the left variable.

    • Extended logical operations
12345678910 #!/bin/sha=1;b="ab"; echo $((a>1?8:9)); ((b!="a"))&& echo "err2";((a<2))&& echo"ok";

Operation Result:

SH testsh.sh
9
Err2
Ok

    • Extending Process Control statements (logical relationships)
12345678910111213141516171819202122 #!/bin/shnum=100;total=0;for((i=0;i<=num;i++));do    ((total+=i));doneecho$total;total=0;i=0;while((i<=num));do    ((total+=i,i++));doneecho$total;if((total>=5050));then    echo"ok";fi

Result of Operation:

SH testsh.sh
5050
5050
Ok

With the double parenthesis operator: [[]],[],test logical operation, already let,expr can be thrown aside.]

Second, SHELL Script

There is one problem that needs to be agreed upon, where custom script recommendations are placed in the/usr/local/sbin/directory, so that the purpose is to better manage the document, and then the administrator who takes over later knows where the custom script is placed and is easy to maintain.

" the basic structure of shell scripts and how to perform them"

Shell scripts are usually suffixed with. SH, which is not to say no. sh This script cannot be executed, just a habit of everyone. So, later you find the. sh suffix file then it must be a shell script. The first line in test.sh must be "#! /bin/bash "It means that the file uses the bash syntax. If you do not set this line, your shell script cannot be executed. ' # ' indicates a comment, as mentioned earlier. Followed by some comments about the script and the author and creation date or version, and so on. Of course these comments are not necessary, if you lazy very, can be omitted, but I do not recommend to omit. Because as you work more hours, you'll be writing more shell scripts, and if one day you look back at a script you've written, it's quite possible to forget what the script was for and when it was written. So it is necessary to write the comments. Another system administrator is not you, if the other administrator to view your script, he can not understand it is very depressed. The script goes down to the command you want to run.

The execution of the shell script is simple, just "sh filename", and you can do so

By default, the document that we edit with VIM does not have execute permission, so we need to add a execute permission so that we can execute the script directly using './filename '. In addition, when using the SH command to execute a shell script, it is possible to add the-X option to view the execution of the script, which helps us debug the script where there is a problem.

The shell script uses the ' Date ' command, which is used to print the current system's time. In fact, the usage of date in the shell script is very high. There are several options that the author often uses in shell scripts:

%y represents the year,%m for the month,%d for the date,%h for the hour,%m for minutes, and%s for seconds

Notice the difference between%y and%y.

The-D option is also frequently used, and it can print dates that are n days old or N day after, and of course you can print n months/years ago or later.

Another day of the week is also commonly used

the shell variables in the script "

Using variables in shell scripts makes our scripts more professional and more like a language, a joke, the role of variables is certainly not for the professional. If you write a shell script that is 1000 lines long, and there is a command or path hundreds of times in the script. Suddenly you think the path does not want to change, that would not be changed hundreds of times? You can use the command for bulk substitution, but it's also cumbersome, and the script looks bloated. The role of variables is to solve this problem.

In test2.sh, do you remember the use of anti-quotes? ' d ' and ' D1 ' appear as variables in the script, defining the variable as "variable name = variable Value". When you reference a variable in a script, you need to add a ' $ ' symbol, which is consistent with the custom variables described earlier in the shell. Let's look at the script execution results below.

Below we use the shell to calculate the two number of the and.

The mathematical calculation is to be enclosed in ' [] ' and to take a ' $ ' outside. The script results are:

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 via keyboard. The script execution process is as follows:

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

There are more concise ways in test4.sh.

The READ-P option is similar to the echo effect. EXECUTE as follows:

Have you ever used such a command "/etc/init.d/iptables restart" in front of the/etc/init.d/iptables file is actually a shell script, why can follow a "restart"? This involves the default variables of the shell script. In fact, shell scripts can be followed by variables when executed, and can be followed by multiple. I would like to write a script, you will understand.

The execution process is as follows:

In the script, you will not be surprised, where comes the $ and $, this is actually a default shell script variables, where the value is the execution of the input 1, and the value of $ is executed when the input of the $, of course, a shell script preset variable is unlimited, this time you understand it. There is another $ A, but it represents the name of the script itself. You might want to modify the script.

You have guessed the result of the execution.

Var= "Hello" #
Var=hello
Var= ' Hello ' #将忽略 $ etc

The above variable assignment is equivalent,

Note the points:

1. There can be no spaces between variables and values, otherwise the interpreter will consider several commands. The habit of many programmers is to leave a blank on both sides of the = sign to look good, but that doesn't work in the shell.

2. The string does not have to be "number or", the above several assignment methods are equivalent. Unless there are spaces or variables between the strings.

such as: var= "Hello World"

var= "$a $b"

the shell logical judgments in Scripts "

If you have learned C or other languages and believe that you are not unfamiliar with if, in shell scripts we can also use if logic to judge. The basic syntax for if judgment in the shell is:

1 ) does not take Else

if Judgment statement; Then

Command

Fi

In If1.sh ((a<60)) Such a form, which is a unique format in the shell script, with a small parenthesis or do not have to error, please remember this format, can be. The result of the execution is:

) with Else

if Judgment statement; Then

Command

Else

Command

Fi

The result of the execution is:

3 ) with elif

If Judgment statement one; Then

Command

Elif Judgment Statement two; Then

Command

Else

Command

Fi

&& here means "and", of course, you can also use | | Indicates "or", execution result:

The above is simply a description of the structure of the IF statement. You can also use "[]" If you are judging the size of the value in addition to the form "(()"). But you cannot use the notation, <, = such symbols, to use-LT (less than),-GT (greater than),-le (less than equals),-ge (greater than or equal),-eq (equals),-ne (not equal).

And look at the If using && | | The situation.

In a shell script, if is also often judged about the file attributes, such as whether it is a normal file or a directory, to determine if the files have read and write execution rights. There are several options that are commonly used:

-E: Determine if a file or directory exists

-D: Determine if the directory is not present and whether it exists

-F: Determine if the file is normal and exists

-R: Determine if the document has Read permissions

-W: Determine if Write permission is available

-X: Determine if executable

If you use the If judgment, the format is: if [-e filename]; Then

In shell scripts, there is a common way to use if to judge logic, which 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 a value other than the above. The following author writes a script that determines whether the input value is odd or even.

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

You can also take a look at the execution process:

Case scripts are often used to write startup scripts for system services, such as those used in/etc/init.d/iptables, so you might want to check them out.

the shell loops in the script "

The shell script is also a simple programming language, of course, the loop is not missing. The commonly used loops have a for loop and a while loop. The structure of the two loops is described below. Do start, done .

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

With this script you can see the basic structure of the For loop:

The condition of the for variable name in the loop;

Command

Done

The condition of the loop can also be written in this form, separated by a space. You can also try, for I in ' ls '; do echo $i; Done and for I in ' cat test.txt '; do echo $i; Done

Take a look at this while loop, the basic format is:

While condition; Do

Command

Done

The result of the script execution is:

In addition, you can ignore the cycle conditions, I often write the monitoring script.

While:; Do

Command

Done

the shell functions in the script "

If you have learned to develop, you must know the function. If you have just come into contact with this concept, there is no relationship, in fact, very well understood. The function is to organize a piece of code into a small unit, and give the small unit a name, when the code is used to call the name of the small unit directly. Sometimes a paragraph in the script is always reused, and if written as a function, use the function name instead of each time, saving time and space.

SUM () in fun.sh is a custom function that you want to use in a shell script

Function name () {

Command

}

Such a format to define functions.

The last script execution process is as follows:

I would like to remind you that in the shell script, the function must be written in the front, not in the middle or the last, because the function is to be called, if it has not yet been called, it will certainly be wrong.

Shell scripts generally introduce so much, and the examples I give are the most basic, so even if you take all the examples completely, it doesn't mean that your shell scripting ability is so good. So the rest of the day you try to practice more, write more scripts, the more scripts you write, the stronger your ability. I hope you can find a book that specializes in shell scripting in-depth study it. Then the author will leave you a few shell script exercises, you'd better not lazy.

1. Write the shell script, calculate 1-100 's and;

2. Write the shell script, ask to enter a number, and then calculate from 1 to enter the number and, if the input number is less than 1, then re-enter until the correct number is entered;

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

4. Write shell scripts, batch build user user_00, User_01, ..., user_100 and all users belong to the Users group;

5. Write a shell script that intercepts the first column in the line containing the keyword ' abc ' in the file Test.log (assuming the delimiter is ":"), then sorts the intercepted numbers (assuming the first column is a number) and prints out the columns with more than 10 repetitions;

6. Write the shell script to determine whether the IP input is correct (IP rules are, N1.N2.N3.N4, where 1<n1<255, 0<n2<255, 0<n3<255, 0<n4<255).

Here are the answers to the exercises:

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/

Fi

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 '} ' Test.log >/tmp/n.txt

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

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

6. #! /bin/bash

Checkip () {

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

A= ' echo $ | Awk-f. ' {print '} '

B= ' echo $ | Awk-f. ' {print $} '

C= ' echo $ | Awk-f. ' {print $} '

D= ' echo $ | Awk-f. ' {print $4} '

For n $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

Fi

Done

Else

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

Return 1

Fi

}

Rs=1

While [$rs-GT 0]; Do

Read-p "Please input the IP:" IP

Checkip $ip

Rs= ' echo $? '

Done

echo "The IP is right!"

Shell Programming Summary

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.