Iv. Loop Structure statements
Common shell loop statements include for loop, while loop, and until loop.
ForLoop
Syntax: for variable in list
Do
Operation
Done
Note: The variable is used inside the loop to refer to the object in the List currently referred.
The list is the object to be operated inside the for loop. It can be a string or a file. If it is a file, it is the file name.
For example, delete all .gz files in the garbage box.
# Delete all file with extension of "GZ" in the dustbin
For I in $ home/dustbin/*. GZ
Do
Rm-F $ I
Echo "$ I has been deleted !"
Done
The execution result is as follows:
[Beichen @ localhost bin] $. f_rmgz
/Home/Beichen/dustbin/Nessus- 4.0.0 .2.tar.gz has been deleted!
/Home/Beichen/dustbin/gftp- 2.2.1 .Tar.gz has been deleted!
WhileLoop
Syntax: While expression
Do
Operation
Done
As long as the while expression is true, the operation between do and done will continue.
UntilLoop
Syntax: Until expression
Do
Operation
Done
Repeat the operations between do and done until the expression is true.
Example:
# Test
# Add from 1 to 100
Total = 0
Num = 0
Until test num-EQ 100
Do
Total = 'expr $ total + $ num' // note that the quotation marks here are backticks, the same below
Num = 'expr $ num + 1'
Done
Echo "the result is $ total"
The execution result is as follows:
[Beichen @ localhost bin] $
The result is 5050!
5. Condition statements
The condition statements in Shell programs mainly include the if statement and the case statement;
IfStatement
Syntax: If expression 1 then
Operation
Elif expression 2 then
Operation
Elif expression 3 then
Operation
.....
Else
Operation
Fi
In Linux, the IF end mark is to write the if statement in turn as fi, while Elif is short for else if.
In theory, there can be an infinite number of Elif instances.
CaseStatement
Syntax: Case string in
Value 1 | value 2)
Operation ::
Value 3 | value 4)
Operation ::
Value 5 | value 6)
Operation ::
*}
Operation ::
Esac
The role of case is to execute the operation after the value when the string is the same as a value. If the same operation has multiple values, use "|" to separate the values. At the end of each case operation, there are two ":" And a semicolon is required.
Example:
Case $ user in
Beichen)
Echo "you are Beichen !";;
Liangnian)
Echo "you are liangnian"; // note that there is only one semicolon
Echo "Welcome !";; // Here are two semicolons
Root)
Echo "you are root! : Echo welcome !";; // Write the two commands in one line and use a semicolon as the Separator
*)
Echo "who are you? $ User ?";;
Esac
Execution result:
[Liangnian @ localhost bin] $ Test
You are liangnian
Welcome!
There are so many basic things about shell programming. If you want to learn more about shell programming, read related books.