[Shell] example of if, for, while flow statement and integer string comparison, shellwhile

Source: Internet
Author: User

[Shell] example of if, for, while flow statement and integer string comparison, shellwhile

Preface:

In fact, Shell is a command interpreter that explains the commands entered by the user and sends them to the kernel. In addition, Shell has its own programming language for editing commands. It allows users to write programs composed of shell commands. The Shell programming language has many features of a common programming language, such as its loop structure and branch control structure. The Shell program written in this programming language has the same effect as other applications.


1. shell flow statement 1, Condition Statement if else if

Sample Code:

[Root @ squid-2 script] # cat s1.sh

#! /Bin/bash

Echo "Please choose project :"

Echo "1: zhu 2: sha"

Read project_no

If [$ project_no = "1"]; then

Echo & quot; 111111 & quot"

Elif [$ project_no = "2"]; then

Echo & quot; 222222 & quot"

Else echo "error"

Fi

[Root @ squid-2 script] #

 

The execution process is as follows:

[Root @ squid-2 script] # sh s1.sh

Please choose project:

1: zhu 2: sha

1

111111

[Root @ squid-2 script] # sh s1.sh

Please choose project:

1: zhu 2: sha

2

222222

[Root @ squid-2 script] # sh s1.sh

Please choose project:

1: zhu 2: sha

3

Error

[Root @ squid-2 script] #

 

 

2, for loop 2.1 for I in

The script is as follows:

[Root @ squid-2 script] # cat host_list.txt

192.168.1.10

192.168.1.11

192.168.1.12

192.168.1.13

[Root @ squid-2 script] #


Test execution result:

[Root @ squid-2 script] # sh s21.sh

The host ip address is: 192.168.1.10

The host ip address is: 192.168.1.11

The host ip address is: 192.168.1.12

The host ip address is: 192.168.1.13

[Root @ squid-2 script] #

 

2.2 for (assign value; condition; Operation statement ))

Script code:

[Root @ squid-2 script] # cat s22.sh

For (I = 1; I <= 10; I ++); do

Echo "the loop number I: $ I ";

Done;

[Root @ squid-2 script] #


Execution result:

[Root @ squid-2 script] # sh s22.sh

The loop number I: 1

The loop number I: 2

The loop number I: 3

The loop number I: 4

The loop number I: 5

The loop number I: 6

The loop number I: 7

The loop number I: 8

The loop number I: 9

The loop number I: 10

[Root @ squid-2 script] #

 

3. while loop usage

Condition Statement structure:

While

Do

Action

Done;


Test script:

[Root @ squid-2 script] # cat s3.sh

#! /Bin/sh

I = 10;

While [[$ I-gt 5]; do

Echo "the loop number of while case is: $ I ";

(I --));

Done;

[Root @ squid-2 script]


Execution result:

[Root @ squid-2 script] # sh s3.sh

The loop number of while case is: 10

The loop number of while case is: 9

The loop number of while case is: 8

The loop number of while case is: 7

The loop number of while case is: 6

[Root @ squid-2 script] #

 

4. until statement

Sample script:

[Root @ squid-2 script] # cat s4.sh

#! /Bin/sh

A = 1;

Until [[[$ a-gt 6]; do

Echo "the until number is: $ ";

(A ++ ));

Done;

[Root @ squid-2 script] #

 

Execution result:

[Root @ squid-2 script] # sh s4.sh

The until number is: 1

The until number is: 2

The until number is: 3

The until number is: 4

The until number is: 5

The until number is: 6

[Root @ squid-2 script] #

 

5. shell SELECT statement 5.1 and use case selection statement (case/esac)

Syntax structure:

Case $ arg in

Pattern | sample) # arg in pattern or sample

;;

Pattern1) # arg in pattern1

;;

*) # Default

;;

Esac

 

Note: pattern1 is a regular expression, which can contain the following characters:

 

* Any string

? Any character

[Abc] a, B, or c

[A-n] any character from a to n

| Multiple options

 

Code script:

[Root @ squid-2 script] # cat s51.sh

#! /Bin/sh

 

Case $1 in

Start | begin)

Echo "start something"

;;

Stop | end)

Echo "stop something"

;;

*)

Echo "Ignorant"

;;

Esac

[Root @ squid-2 script] #


PS: execution result. here we need to include the parameter. The parameter value is within the start, begin, stop, and end parameters before). If the parameter is included, "Ignorant" is returned ":

[Root @ squid-2 script] # sh s51.sh start

Start something

[Root @ squid-2 script] # sh s51.sh begin

Start something

[Root @ squid-2 script] # sh s51.sh end

Stop something

[Root @ squid-2 script] # sh s51.sh stop

Stop something

[Root @ squid-2 script] # sh s51.sh test1

Ignorant


5.2. How to Use the select statement (generate menu selection)

Syntax structure:

Select variable name in seq variable

Do

Action

Done


The Code is as follows:

Cat s52.sh

#! /Bin/sh

Select param in "begin" "end" "exit"

Do

Case $ param in

"Begin ")

Echo "start something"

;;

"End ")

Echo "stop something"

;;

"Exit ")

Echo "exit"

Break;

;;

*)

Echo "Ignorant"

;;

Esac

Done;


Execution result:

[Root @ squid-2 script] # sh s52.sh begin

1) begin

2) end

3) exit

#? 1

Start something

#? 2

Stop something

#? 3

Exit

[Root @ squid-2 script] #

PS: During execution, only exit can be entered to exit the execution window.

Note: select is a loop selection, which is generally used with case statements.


2. shell statement comparison operator 1, integer comparison

Rule Description:

 

-Eq equals to if ["$ a"-eq "$ B"]

-Ne is not equal to if ["$ a"-ne "$ B"]

-Gt is greater than if ["$ a"-gt "$ B"]

-Ge is greater than or equal to if ["$ a"-ge "$ B"]

-Lt is less than if ["$ a"-lt "$ B"]

-Le is less than or equal to if ["$ a"-le "$ B"]

<Less than (double parentheses required) ("$ a" <"$ B "))

<= Less than or equal to (...) ("$ a" <= "$ B "))

> Greater than (...) ("$ a"> "$ B "))

> = Equal to or greater than (...) ("$ a"> = "$ B "))

PS: AWK can be used for small data comparison

 

Sample Code:

[Root @ squid-2 script] # cat com1.sh

A = $1

B = $2

If ["$ a"-eq "$ B"]; then

Echo "a = B true ."

Elif [! "$ A"-gt "$ B"]; then

Echo "a> B true ."

Else echo "a <B true ."

Fi

[Root @ squid-2 script] #


The test results are as follows:

[Root @ squid-2 script] # sh com1.sh 1 1

A = B true.

[Root @ squid-2 script] # sh com1.sh 1 2

A> B true.

[Root @ squid-2 script] # sh com1.sh 1 0

A <B true.

[Root @ squid-2 script] #


2. String comparison 2.1, standard and use

Rule Description:

= Equals to if ["$ a" = "$ B"]

= Equivalent to =

! = Not equal to if ["$ a" = "$ B"]

<Less than, in the order of ASCII letters:

If [["$ a" <"$ B"]

If ["$ a" \ <"$ B"] # Escape <

> Greater

-Z string is null, that is, the length is 0

-N string is not null, that is, the length is not 0

 

Sample Code:

[Root @ squid-2 script] # cat com2.sh

A = $1

B = $2


#1 the first method to implement

If ["$ a" x = "$ B" x]; then

Echo "a = B"

Elif [! "$ A" x = "$ B" x]; then

Echo "! = B"

Else echo "others"

Fi

 

#2 the second method to implement

If ["$ a" x = "$ B" x]; then

Echo "a = B"

Elif ["$ a" x! = "$ B" x]; then

Echo "! = B"

Else echo "others"

Fi

 

Test execution result:

[Root @ squid-2 script] # sh com2.sh ccb aaa

A! = B

A! = B

[Root @ squid-2 script] # sh com2.sh ccb

A = B

A = B

[Root @ squid-2 script] #

[Root @ squid-2 script] #


2.2. Notes

Notes for equal judgment:

The method to compare the two strings is as follows:

If ["$ a" x = "B" x]; then

The key points here are:

1. Use a single equal sign

2 Note that there is a space on both sides of the equal sign: This is a unix shell requirement.

3. Note that the last x of "$ a" x is specially arranged, because when $ test is null, the above expression becomes x = bx, obviously, they are not equal. Without this x, the expression returns the error [: =: unary operator expected

 

[[$ A = z *] # true if $ a starts with "z" (pattern matching)

[[$ A = "z *"] # If $ a is equal to z * (character matching), the result is true.

[$ A = z *] # File globbing and word splitting will occur

["$ A" = "z *"] # If $ a is equal to z * (character matching), the result is true.

 

About File globbing:

For a bit of explanation, Fileglobbing is a stenographer of files, for example, "*. c" is, and then ~ Yes.
But file globbing is not a strict regular expression, although the structure is similar in most cases.

 

Comparison of special characters:
! = Not equal to, such as: if ["$ "! = "$ B"]
This operator uses pattern matching in the [[] structure.
<Less than, in the ASCII alphabetic order. For example:
If [["$ a" <"$ B"]
If ["$ a" \ <"$ B"]
Note: "<" must be escaped in the [] structure.
> Greater than, in the ASCII alphabetic order. For example:
If [["$ a"> "$ B"]
If ["$ a" \> "$ B"]
Note:In the [] structure, ">" must be escaped.

-Z string is "null". The length is 0.
-N string is not "null"
Note:
To use-n in the [] structure, you must use "" To cause variables. Use a string that is not! -Z
Or the strings that are not referenced by "" are put in the [] structure. Although it can work normally, it is not safe. It is a good habit to use "" To test strings.


2.3, judge whether the string is null

Sample Code:

[Root @ squid-2 script] # cat com3.sh

#! /Bin/bash

A = $1

If [-z "$ a"]; then

Echo "a is empty ."

Else echo "a is a object ."

Fi

[Root @ squid-2 script]


Test execution result:

[Root @ squid-2 script] # sh com3.sh

A is a object.

[Root @ squid-2 script] # sh com3.sh

A is empty.

[Root @ squid-2 script] #

 

3. File judgment

Rule Description:

-E file exists
-File a exists (discarded)
-F the file to be tested is a regular file (normal file, non-directory or device)
-S file length is not 0
-D. the object to be tested is a directory.
-B. the object to be tested is a block device.
-C: the object to be tested is a character device.
-P: the object to be tested is a pipeline.
-H the file to be tested is a symbolic connection
-L the file to be tested is a symbolic connection.
-S (uppercase) the file to be tested is a socket
-T is the file descriptor associated with a terminal device. The stdin [-t0] or [-t1] used to detect scripts is a terminal.
-The r file has read permission for the user who runs the script
-W file has write permission for the user who runs the script
-The x file has the execution permission for the user who runs the script.
-U set-user-id (suid) indicates the file, that is, the root permission file that common users can use, implemented through chmod + s file
-K: Set the pasting position
-O the user who runs the script is the file owner.
The group-id of the-G file is the same as the user who runs the script.
-N: indicates whether the object has been modified since it was last read.

F1-nt f2 file f1 is newer than f2
Is f1-ot f2 earlier than f2?
Does f1-ef f2 file f1 and f2 hard connect to the same file?

 

Sample script code:

[Root @ squid-2 script] # cat com4.sh

#! /Bin/bash

A = $1

File = $2

If [-d $ a]; then

Echo "it is a directory ."

Elif [-f "$ a"]; then

Echo "it is a file ."

Else echo "no parameter ."

Fi

 

The test result is as follows:

[Root @ squid-2 script] # sh com4.sh log1

It is a file.

[Root @ squid-2 script] # sh com4.sh old

It is a directory.

[Root @ squid-2 script] #

 


References:

Http://www.cnblogs.com/chengmo/archive/2010/10/14/1851434.html

Http://blog.csdn.net/yf210yf/article/category/1475895

 


Loop and judgment statement format in bash shell

1) [[] is basically the same as [], but [[] is highly fault tolerant in some situations ;(()) is the meaning of the direct arithmetic operation, such as (I ++ ));
2, [] indicates test. You will know man test. According to the program, it is better to use lt gl eq for arithmetic calculation, and character comparison>, <..
3, not necessarily. spaces in the variable must be added. For example, if you do not use name abc, the $ name abc and "$ name abc" are different.

In linux shell programming, if statements cannot determine whether the variables are equal

($ Num1! = $ Num2) is an arithmetic expression.
Use ($ num1-$ num2 ))
Or [[$ num1! = $ Num2]

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.