Shell script application and loop statements

Source: Internet
Author: User

Shell script application and loop statements

1. bash wildcard:

1 .? // Any single character

2. * // 0 or multiple characters

3. [] // any character in the interval

4.; // split the command, ignore the execution result of the previous command, and continue to execute the subsequent command

5. & // The background execution Program

6. & // The preceding command is successfully executed. The returned value is 0, and the subsequent command is executed.

7. | // The preceding command fails to be executed. If the returned value is not 0, the subsequent command is executed.

8. | // MPs queue

9. () // enable the sub-shell and execute the commands in it

10. {} // The command is executed in the Current shell

11. >>> // output redirection

12. <// input redirection

13. $ // define variables

14. \\// escape; command line

15. ''// The execution result of calling the command; nesting is not allowed.

16.-// The hyphen (-); the prefix of the command options ,---

17. ''// strong quote symbol; special characters are blocked

18. "" // weak referenced symbols; ''$ \ these three symbols cannot be blocked

19.: // indicates a null operation. The returned value is always 0. while Loop

20. [: alnum:] // letters + numbers

21 [: alpha:] // letter

22 [: lower:] // lowercase letter

23 [: upper:] // uppercase letter

24 [: digit:] // decimal number

25 [: punct:] // symbol

26 [: space:] // blank character (space "tab ")

27 [[: alnum:] // any letter or number [a-Z0-9]

28 [^ [: alnum:] // returns the inverse

[[: Alnum:]!]

2. Variables

1. Note

(1) = do not have spaces on both sides

(2) do not use $ as the variable name.

(3) variable name length-256 characters, case sensitive

2. How to reference

(1) Direct reference:

Echo command

-E: Enable \ (backslash) to control the conversion of characters (\ t \ n)

-N: cancels the linefeed.

[Root @ tx1 ~] # Echo "123 \ t234"

123 \ t234

[Root @ tx1 ~] # Echo-e "123 \ t234"

123 234

[Root @ tx1 ~] # Echo-e "123 \ n234"

123

234

[Root @ tx1 ~] # Echo-n "123 \ t234"

123 \ t234 [root @ tx1 ~] #

(2) indirect reference

[Root @ tx1 ~] # A = B

[Root @ tx1 ~] # B = c

[Root @ tx1 ~] # Echo $

B

[Root @ tx1 ~] # Echo $ {! A}

C

(3) Scope of Variables

@ 1 in the current shell, the defined variable is called the local variable-local variable.

@ 2 global variable-environment variable, export converts local variable to global variable. It only acts on the sub-shell.

[Root @ tx1 ~] # X = 123

[Root @ tx1 ~] # Echo $ x

123

[Root @ tx1 ~] # Bash

[Root @ tx1 ~] # Echo $ x


[Root @ tx1 ~] # Exit

Exit

[Root @ tx1 ~] # Export x

[Root @ tx1 ~] # Bash

[Root @ tx1 ~] # Echo $ x

123


(4) view the Defined variables

@ 1. set to view all variables

@ 2. env view global variables

@ 3. unset cancel variable unset + variable name

@ 4. Set the variable to read-only: readonly + variable name


(5) Location Parameter $

Note: The location parameter is transmitted from the command line to the script, or to the function, or to a variable.

$0 command itself

$1 $2... $ {10}

$ # Number of parameters

$ * All Parameters


$ @ All parameters (must be referenced)

$ Process number of the previous command

$? Result returned by the previous command

$ _ Last parameter of the previous command

$! The last process number that enters the background command

$ () Is equivalent''

$ () Is equivalent to $ [] for mathematical operations, but can only be an integer.

(6) Replacement of Variables

Note: It is used for matching or determining whether a variable exists.

@ 1. $ {variable name:-string}: If the variable is empty, a string is returned; otherwise, the value of the variable is returned.

@ 2. $ {variable name: + string}: If the variable has a value, replace the variable with a string. Otherwise, a null value is returned.

@ 3. $ {variable name: = string}: If the variable has no value, assign the string to the variable; otherwise, return the value of the variable.


@ 4. $ {variable name :? Prompt message}: If the variable has no value, a prompt is returned.

@ 1.

[Root @ tx1 ~] # Echo $

[Root @ tx1 ~] # Echo $ {a:-123}

123

[Root @ tx1 ~] # B = abc

[Root @ tx1 ~] # Echo $ {B:-123}

Abc


@ 2.

[Root @ tx1 ~] # Echo $ {a: + 123}

[Root @ tx1 ~] # Echo $ {B: + 123}

123


@ 3.

[Root @ tx1 ~] # Echo $

[Root @ tx1 ~] # Echo $ B

Abc

[Root @ tx1 ~] # Echo $ {a: = 123}

123

[Root @ tx1 ~] # Echo $

123

[Root @ tx1 ~] # Echo $ {B: = 123}

Abc

[Root @ tx1 ~] # Echo $ B

Abc


@ 4.

[Root @ tx1 ~] # Unset

[Root @ tx1 ~] # Echo $ {:?}

Bash: a: parameter null or not set

[Root @ tx1 ~] # Echo $ {:? No variable set}

Bash: a: No variable is set

(7) variable matching mode

#: Minimum match starting from the header of the variable value, and then deleting

#: Start the maximum match from the header of the variable value, and then delete it

%: Minimum match starts from the end of the variable value and then deletes it.

%: The maximum matching starts from the end of the variable value and then deletes it.

: Num1: num2: Specifies the value of the truncated variable. num1 indicates the starting position, num2 indicates the number of truncated characters, and 0 indicates the first character.

@ 1.

[Root @ tx1 ~] # Echo $ {pth #*/}

Usr/bin/local/bin/all

[Root @ tx1 ~] # Echo $ {pth ##*/}

All

@ 2.

[Root @ tx1 ~] # Echo $ {pth % /*}

/Usr/bin/local/bin

[Root @ tx1 ~] # Echo $ {pth % /*}


[Root @ tx1 ~] #

@ 3.

[Root @ tx1 ~] # Echo $ {pth: 0: 6}

/Usr/B

[Root @ tx1 ~] # Echo $ {pth: 3: 6}

R/bin/

Iii. If statement

1. single branch if statement.

If [conditional expression]; then

Command ;...

Fi

Note: when the conditions are met, the statement after then is run. If the conditions are not met, the judgment statement is exited.


2. Dual-branch if statement

If [conditional expression]; then

Command ;...

Else

Command ;...

Fi

Note: when the conditions are met, the statement after then is run. If the conditions are not met, the statement after else is run.

3. conditional expression (man test)

(1) string judgment

Str1 = str2 check if str1 and str2 are the same

Str1! = Str2 check if str1 and str2 are different

Str1 <str2 check if str1 is smaller than str2

Str1> str2 check if str1 is greater than str2

-N str1 check if the str1 length is greater than 0

-Z str1: Check whether the str1 length is 0

= ~ : Determines whether the string on the Left can be matched by the pattern on the right. [["$ opt1" = ~ Pattern], NOTE: When judging a string, the string should be wrapped up with "" (more detailed man test)


(2) integer judgment

-Eq equals

-Ge is greater than or equal

-Gt greater

-Le is less than or equal

-Lt is less

-Ne is not equal

(3) file judgment

-B file: determines whether a block file exists.

-C file: determines whether a character file exists.

-D file: determines whether the file exists and is a directory file

-E file: determines whether a file exists.

-F file: determines whether a file exists and is a common file.

-H file: determines whether a symbolic link exists.

-R file: determines whether the file exists and is readable.

-S file determines whether or not the file exists and is not empty

-W file: determines whether the file exists and can be written

-X file: determines whether the file exists and is executable.

-O file: determines whether the user exists and the user is the current user.

-G file: determines whether the group exists and the group is the current group.


(4) conditional statements

And-

If [expression 1-a expression 2]


Or-o

If [expression 1-o expression 2]


Not!

If [! Expression]

Note

[[Expression 1 & Expression 2] =-

[[Expression 1 | expression 2] =-o

[[! Expression] =!

If expression

Then

Command

Elif expression

Then

Command

Elif expression

Then

Command

......

Else

Command

Fi


(5) Multiple judgments


Example 1.

Note: read-p

-T timeout-t 3 (seconds)

-S input does not show back, (password)

[Root @ tx1 ~] # Vim tx1.sh

#! /Bin/bash

# This is a script for determining the file type

If [-B/dev/hda1]

Then

Echo "Block device"

Fi


If [-d/etc]

Then

Echo "directory"

Fi

If [-e/etc/passwd]

Then

Echo "normal file"


Fi

[Root @ tx1 ~] #./Tx1.sh

Block Device

Directory

Common File

Example 2

#! /Bin/bash

# This is a script to determine whether a user exists.


Read-p "enter a user name:" uname

If ["$ uname" = ""]

Then

Echo "error"

Else

Ifgrep "^ \ <$ uname \>"/etc/passwd &>/dev/null

Then

Echo "this user exists"

Else

Echo "this user does not exist"

Fi

Fi

Example 3 (nested if)

Note: terminal Encryption

[Root @ tx1 ~] # Vim/etc/bashrc

Read-p "Enter the User name:" uname

If ["$ uname" = "root"]

Then

Read-p "enter the password:" pass

If ["$ pass" = "123"]

Then

Echo "welcome root"

Else

Exit 1

Fi

Else

Exit 2

Fi

After opening a new terminal

Enter the User name: root

Enter Password: 123

Welcome root

[Root @ tx1 ~] #

Example 4

#! /Bin/bash

# Use double conditions to determine the user name and password

Read-t 5-p "username:" uname

Read-s-p "password:" pass

Echo


If ["$ uname" = "root"-a "$ pass" = "123"]

Then

Echo "welcome root"

Else

Echo "go out"

Fi

Example 5

#! /Bin/bash

# Determining the type of a user

Read-p "enter a user name:" uname

Id = 'grep "^ \ <$ uname \>"/etc/passwd | cut-d:-f 3'

If ["$ uname" = ""]

Then

Echo "error"

Elif[ $ id-ge 500]

Then

Echo "$ uname is a common user"

Elif [$ id-lt 500-a $ id-ge 1]

Then

Echo "$ uname is a system user"

Else

Echo "$ uname is a Super User"

Fi

[Root @ tx1 ~] #./Tx5.sh

Enter a user name: root

Root is a Super User

[Root @ tx1 ~] #./Tx5.sh

Enter a user name: tx

Tx is a common user

[Root @ tx1 ~] #./Tx5.sh

Enter a user name: bin

Bin is a system user

[Root @ tx1 ~] #./Tx5.sh

Enter a user name:

Error

Iv. case multi-branch judgment

Syntax:

Case $ variable in

Value1)

Commands

;;

Value2)

Commands

;;

......

*)

Commands

;;

Esac

Example 1.

Note: For example, the age of a person: 0 infants, 1-9 children, 1-19 teenagers, 20-29 young people, 30-39 middle-aged people, 40-old people

#! /Bin/bash

# Determine a person's age group

Read-p "Enter the age of a person:" age

Case $ age in

0)

Echo "baby"

;;

[1-9])

Echo "children"

;;

1 [0-9])

Echo "juvenile"

;;

2 [0-9])

Echo "Youth"

;;

3 [0-9])

Echo "middle-aged"

;;

*)

Echo "elder care"

;;

Esac

[Root @ tx1 ~] #./T1.sh

Enter the age of a person: 3

Children

[Root @ tx1 ~] #./T1.sh

Enter a person's age: 67

Old

[Root @ tx1 ~] #./T1.sh

Enter a person's age: 20

Youth


V. For Loop

Note: The for loop provides a list of elements in advance, and then uses variables to traverse the list of elements. Each time an element is accessed, the loop body is executed until the element access is completed.
1. Syntax:

For variable in Variable list

Do

Commands

Done

Example 1. Use the for loop to output three numbers

#! /Bin/bash

For I in "$ *"

Do

Echo $ I

Done


For j in "$ @"

Do

Echo $ j

Done

[Root @ tx1 ~] #./T3.sh 1 2 3

1 2 3

1

2

3

Example 2: Copy all index.html under/usr/share/doc/to the/tmp/index/directory, and check whether/tmp/index/exists.

#! /Bin/bash

If [-d/tmp/index]

Then

Num = 1

For I in $ (find/usr/share/doc-name index.html)

Do

/Bin/cp $ I/tmp/index/index.html. $ num

Num = $ ($ num + 1 ))

Done

Else

Mkdir/tmp/index

Num = 1

For I in $ (find/usr/share/doc-name index.html)

Do

/Bin/cp $ I/tmp/index/index.html. $ num

Num = $ ($ num + 1 ))

Done

Fi

6. While statement

Syntax:

While [expression]

Do

Commands

Update expression

Done


Expression: determines whether a loop is executed.

The Return Value of the expression is true, $? = 0, execute the command

The Return Value of the expression is false, ending the loop.

:; True: the returned value is always true.

Example 1. Create 5 Users in batches

[Root @ tx1 ~] #Catt1.txt

Tx1

Tx2

Tx3

Tx4

Tx5

[Root @ tx1 ~] # Cat t6.sh

#! /Bin/bash

While read line

Do

Uname = 'echo $ Line'

Useradd $ uname

Echo $ uname | passwd $ uname -- stdin

Done </root/t1.txt

Example 2. Signal capture

Note: signal capturing, trap, 1 2 9 15, and signal 9 cannot be captured.

#! /Bin/bash

# Signal capture


Trap "echo process continues" 1


While:

Do

Echo "hello"

Sleep 3

Done

[Root @ tx1 ~] # Ps-

PID TTY TIME CMD

18810 pts/2 00:00:00 bash

18813 pts/2 00:00:00 sleep

18814 pts/1 00:00:00 ps

[Root @ tx1 ~] # Kill-1 18810


[Root @ tx1 ~] #./T7.sh

Hello

Hello

Hello

Hello

The process continues.

Hello

VII. Until statement

Syntax:

Until [expression]

Do

Commands

Update expression

Done


Expression: determines whether a loop is executed.

When the return value of an expression is false, execute a loop, $? Non-0

When the return value of an expression is true, the loop ends.

Example 1.

#! /Bin/sh


A = 10;

Until [[$ a-lt 0]; do

Echo $;

(--));

Done;

[Root @ tx1 ~] #./T8.sh

10

9

8

7

6

5

4

3

2

1

0

8. shift, break, and continue

Example 1

#! /Bin/bash

Until [$ #-eq 0]

Do

Echo $ *

Shift

Done

[Root @ tx1 ~] #./Tt1.sh 1 2 3 4 5 6

1 2 3 4 5 6

2 3 4 5 6

3 4 5 6

4 5 6

5 6

6

Example 2. break Out Loop

#! /Bin/bash

For I in 'seq 1 2'

Do

For j in 'seq 1 3'

Do

Echo $ j

If [$ j-eq 2]

Then

Break # Jump out of the current loop

Fi

Done

Done

[Root @ tx1 ~] #./Tt2.sh

1

2

1

2


Example 3

#! /Bin/bash

For I in 'seq 1 10'

Do

For j in 'seq 1 3'

Do

Echo $ j

If [$ j-eq 2]

Then

Break 2 # Jump out of layer 2nd Loop

Fi

Done

Done

[Root @ tx1 ~] #./Tt3.sh

1

2

Example 4 (continue ends the cycle)

#! /Bin/bash

For I in 'seq 13'

Do

For j in 'seq 1 3'

Do

If [$ j-eq 2]

Then

Continue # end this cycle

Fi

Echo $ j

Done

Done

[Root @ tx1 ~] #./Tt4.sh

1

3

1

3

1

3

Example 5

#! /Bin/bash

For I in 'seq 13'

Do

For j in 'seq 1 3'

Do

If [$ j-eq 2]

Then

Continue 2 # end the cycle at Layer 1

Fi

Echo $ j

Done

Done


[Root @ tx1 ~] #./Tt5.sh

1

1

1


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.