Shell Script Programming Learning notes (i)

Source: Internet
Author: User

First, the script format

Vim shell.sh

#!/bin/bash//Declaration script interpreter, this ' # ' is not a comment, the rest is a comment

#Program://program Content description

#History://Time and author

Ii. Types of Shell variables

User-defined variables: defined, modified, and used by the user

With defined variables: Bash with special variables defined, cannot be directly modified

Positional variables: Passing parameters to the program through the command line

1. Define variables:

Variable names start with an English letter or underscore, and are case-sensitive.

Format: Variable name = value

Output variable: echo $ variable Name

2. Keyboard input is variable content:

Format: Read [-P ' info '] variable name

such as: read-p "Pewase Input your Name:" Name

3. Effect of different quotation marks on variables

Double quotation mark "": resolvable variable, $ symbol is variable prefix.

Single quote ': Do not parse the variable, $ is a normal character.

Anti-quote ': Outputs the result of the command execution to the variable.

Three, Shell condition test

1. Test command:

Purpose: Tests whether a particular expression is true or not, and when the condition is set, the return value after the command executes is 0, otherwise the other number.

Format: Test conditional expression [conditional expression] (Note: A space exists between [] and an expression)

2. Common Test Types:

Test file status

Format: [operator file or directory]

such as: if [-d/etc]

Then

echo "exists"

Else

echo "NOT EXISTS"

Fi

Common Test operators:

-D: Test for Directory

-E: Test whether the directory or file exists

-F: Test for file

-R: Tests whether the current user has Read permissions

-W: Tests whether the current user has write permissions

-X: Tests whether the current user has Execute permissions

-L: Test for Symbolic Link file

string comparison

Format: [String 1 = string 2]

[String 1! = String 2]

[-Z string]

Example: Read-p ' name: ' Name

Read-p ' Pass: ' Pass

if [$name = ' admin '] && [$pass = ' 123 ']

Then

Echo ' Login successful '

Else

Echo ' Login failed '

If

Common Test operators:

=: string content is the same.

! =: string contents are different.

-Z: The string content is empty.

Integer value Comparison

Format: [Integer 1 operator integer 2]

such as: age=30

If [$age-ge 18]

Then

echo "Adult"

Else

echo "Underage"

Fi

Common Test operators:

-eq: Equals

-ne: Not equal to

-GT: Greater Than

-LT: Less than

-le: greater than or equal to

-ge: Less than or equal to

Logic test

Format: [expression 1] operator [expression 2]

Common operators:

-A or &&: Logic and

-O or | |: Logical OR

!: Logical Non-

Iv. Process judgment:

1. Condition judgment

A, if statement

Format:

Single branch:

An IF condition expression

then command sequence

Fi

such as: age=30

If [$age-ge 18]

Then

echo "Adult"

Else

echo "Underage"

Fi

Multiple branches:

An IF condition expression

then command sequence

elif command sequence

Fi

such as: score=87

If [$score-lt];then

Echo ' 60 or less '

elif [$score-gt] && [$score-lt];then

Echo ' 60~70 '

elif [$score-ge] && [$score-lt];then

Echo ' 70~ 80 '

Else

Echo ' excellent '

Fi

B. Case

Format: Case $ variable name in

"First variable content")

;;

"Second variable content")

;;

*)////The last variable content will be represented by * for other values, not including the contents of the preceding variables

;;

Esac

such as: Case $ in

Start

Echo ' Start MYSQL service. '

;;

Stop

Echo ' Stop MYSQL service. '

;;

*)

echo "Usage: $ start|stop"

;;

Esac

2. Cyclic control

Jump out of this cycle: continue

End Loop: Break

A, while loop

Format: While [conditional expression]

Do

Procedure Paragraph

Done

such as: num=3

While [$num-GT 0]

Do

Echo $num

num=$ (($num-1))

Done

b, for Loop

Format: for Var in con1 Con2 Con3

Do

Program Segment

Done

Such as:

For i in User0 user1 user2 User3

Echo $i

Done

Format: for ((i=0;i<10 1++))

Do

Program Segment

Done

such as: for ((i=0;i<10;i++))

Do

Echo $i

Useradd user$i

Echo 123 | Password--stdin_user$i

Done

3. Function use

Define a function: At the very front of the program

Function name () {} or Function function name {}

such as: function PrintIt () {

echo "Your choice is $"

}

Invocation: Direct use of function names

Example: PrintIt 1

Pass parameters: Function name parameter 1 parameter 1

Example: PrintIt 2

Five, Shell text operation

1. Use of Find lookup commands

Find. -name "*.text"//Search for files with txt suffix in the current directory

Fing.-name "[a-z]*"//Find the first letter of the file in the current directory

Find/etc-name "host*"//Find files starting with host in/etc directory

Find. -perm 755//Find the file with property 755 in the current directory

Find-user root//In the current directory look for files that belong to the master root

Find/var-mtime-5//Find files with change time within 5 days under/var

Find/var-mtime +3//Find the file changed 3 days before/var

Find/etc-type d//Find a directory file with file type D

Find/etc-typt L//Find linked files with file type L

Find. -size +1000000c//Find files with file size in 1M

2. Regular expressions

^linux//Start with Linux

$php//End of PHP

. Match any single character

. +//Match any number of characters

. *//Match 0 or more characters

[0-9a-z]//Match any one of the characters in []

(Linux) +//occurrences of multiple Linux words

(web) {2}//web has appeared more than 2 times

\//Translation

3, grep detailed

grep "Li QQ" *//Find Li qq file in all files

Grep-c "File" A//Find out how many rows in a file match

Grep-n "File" A//Find out in the file how many rows match file, displaying both line and line numbers

Grep-i "File" A//Find file in files, not case sensitive

Grep-v "File" A//filter out the row where file is located

Grep-e "2017:22:5[0-9]" A//Find the line in the file where the time is in 2017:22:50 to 59

Grep-e "^[^210]" A//Find the line in the file for the No. 210 in the cold

Grep-e "H*p" A//find lines that contain H and P

Grep-e "[5-8][6-9][0-3]" A//find rows greater than 560 less than 893

Grep-e "^d" A//find lines that start with D in a file

Grep-e "^[^d]" A//Find lines in a file that do not start with D

4. awk command:

Summary: Awk is a powerful text analysis tool that is especially powerful when it comes to analyzing data and generating reports, compared to grep lookups and sed editing. To put it simply, awk reads the file line-by-row, using spaces as the default delimiter to slice each row, and then perform various analytical processing of the cut.

The most basic function of the awk language is to browse and extract information in a file or string based on the specified rules, before awk extracts the information for additional text operations. A complete awk script is typically used to format the information in a text file.

Typically, awk is treated as a unit of a file's behavior. awk processes the text by executing the corresponding command for each line that receives the file.

Format: awk ' {pattern + action} ' {filenames}

Pattern: Finding Content

Action: matching rule

awk ' {pring $} ' access.log//find each column in a file

awk ' {print $ \ t ' $7} ' access.log//Find the first and seventh columns in a file

Cat File | awk ' $!~/192.168.31.25/' |grep "PHP"//Match IP address statistics,!~ to mismatched

Example: For i in ' cat/etc/passwd | Head | Awk-f: ' {print '} '

Do

Echo $i

Done

-F---what symbol to split

Head---How many lines to go before, default is 10 rows

5, sed line positioning use

Summary: SED is a non-interactive editor. It does not modify the file unless you use Shell redirection to save the results. By default, all output lines are printed to the screen.

Options Function
-E Multiple edits, which are used when multiple SED commands are applied to an input line
-N Cancel the default output
-F Specify the file name of the SED script

Sed-n ' 2 ' p file//print only the second line, not print other lines

Sed-n ' 1,4 ' p file//record from first row to line fourth

Sed-n '/los/' p file//print a row matching Los

Sed-n ' 4,/los/' p file//print all rows from line fourth to match Los

Sed ' d ' File//bar the first and second lines are all deleted

6, Uniq line positioning use

Summary: The UNIQ command is used to report or ignore duplicate rows in a file and is generally used in conjunction with the sort command.

Syntax Uniq (options) (parameters)

Options:

-C or--count: Displays the number of occurrences of the row next to each column;

-D or--repeated: Displays only the rows that appear repeatedly;

-f< field > or--skip-fields=<;: Ignores comparison of the specified field;

-s< character position > or--skip-chars=< character position;: Ignores the comparison of the specified character;

-U or--unique: Show only one row at a time;

-w< character position > or--check-chars=< character position;: Specifies the character to compare.

Uniq-c File//Print the number of occurrences of a repeating line immediately

uniq-d File//print only duplicate rows

awk ' {print '} '/var/log/httpd/access_log | SORT|UNIQ-C//The Apache website All Access IP statistics, and print out the number of statistics.

7, Spli line positioning

Summary: You can split a large file into many small files, and sometimes you need to split the files into smaller pieces, such as creating a log for readability.

Syntax: Split (option) (file) PREFIX

Options:

-B: The value is the size of each output file, in bytes.          -C: The maximum number of bytes for a single line in each output file.          -D: Use a number as a suffix. -L: The value is the size of the number of columns per output file.
PREFIX: Represents a leader character that can be used as a leading file for cutting files.

Split-2 file SPT//Generate FILEAB,FILEAC....FILEAI and other files, the A file is divided into one file per line, each file prefix is the beginning of the files.

Shell Script Programming Learning notes (i)

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.