Learning bash notes-Process Control

Source: Internet
Author: User

Bash supports the following process control structures:

If/else: If a condition is true or false, execute an execution list.

For: fixed number of times to execute a statement list.

While: When a condition is true, a statement list is repeatedly executed.

Until: execute a Statement List repeatedly until a condition is true.

Case: execute one of several statement lists based on the value of a variable.

Select: allows you to select a menu from an optional list.


1. If/else

The simplest type of flow control structure is the conditional statement embedded in the IF Statement of bash. When you choose to do or not do something, or use a true or false conditional expression

You can use conditional statements when selecting an operation from a few tasks. Conditional statement to test whether the command contains shell variable values, text character features, and

Success and other factors.

The IF structure syntax is as follows:

If condition

Then

Statements

[Elif Condition

Then statements]

[Else

Statements]

Fi


1.1 exit status and return the exit status of the last statement in the list after the if keyword is checked. This list usually indicates a statement. If the status is 0, the condition evaluation is true. If it is another statement, the condition is false. This condition also applies to each condition in the Elif statement. For example, the content of A. Sh is as follows: if CD $1;
Then
Echo "OK"
Else
Echo "NG"
Fi
Execution result: #./A. Sh 1
./A. sh: Line 1: CD: 1: no such file or directory
NG
#./A. sh/dev
OK
The semicolon in the script is used to separate each syntax keyword or command. The above semi-colon format is the same as that for non-writing, but if it is written as follows:
If CD $1; then Echo "OK"; else echo "NG"; FI
If you do not enter a semicolon, an error occurs.

If the second feature is required, the return n statement causes the function containing it to exit with status n. N is actually optional. It is the exit status of the last command by default. A function that does not end with a return statement will return the status returned by the last statement. Return can only be used in functions and shell scripts executed using source. In comparison, the exit n statement exits the entire script regardless of the number of layers nested in the function.
. Combined exit state bash allows you to logically combine exit states so that you can test multiple contents at a time. Execute statement1 when the syntax statement1 & statement2 indicates. If the exit status is 0, execute statement2. Syntax statement1 | statement2: Execute statement1. If the exit status is not 0, execute statement2.
. The conditional test shell uses the [...] structure to test various conditions. You can use this structure to check the various attributes of a file, or compare the updates of the two files, and compare the strings. [# Condition #] returns an exit status, indicating whether the condition is true. Spaces in [] are required.
1.3.1. If the string is compared to str1 = str2, str1 matches str2str1! = Str2str1 does not match str2str1 \ <str2str1 less than str2str1 \> str2str1 greater than str2-n str1str1 is not null, that is, the length is greater than 0. You can also directly use ["$ str1"]. -Z str1str1 is null, that is, the length is 0.
Note that escape is required when <,> is used, and there must be no less space on both sides of the comparison character, otherwise it will be considered as a string. For example, the content of A. Sh is as follows: str1 = "132"
Str2 = "125"
If [$ str1 \> $ str2] Then
Echo "str1 is bigger than str2"
Else
Echo "str1 is not bigger than str2"
Fi
Execution result: str1 is bigger than str2.
The script compares the ASCII code of Characters in the string to determine the size.
1.3.2. File Attribute check-D File
File exists and is a directory.
-E File
File exists.
-F File
File exists and is a regular file (that is, it is not a directory or another special type file)
-R File
Read the object
-S file
The file exists and is not empty.
-W File
Write Permission on file
-X file
You have the executable permission on the file. If it is a directory, you have the Directory Search permission.
-O file
You are the owner of the file.
-G file group ID matches your ID (if you are in multiple groups, match one of them)
File1-nt file2
File1 is newer than file2
File1-ot file2
File1 is older than file2

You can also add it before the conditional expression! The symbol denies its true value, so that only when the expression is false ,! The expr value is true. In addition, you can use parentheses to escape with diagonal lines to prevent shell from specially grouping values or using two unintroduced logical operators:-A (and) and-O (OR) to implement complex logical expressions of conditional operators. For example, if [\ (-N $ dirname1 \)-A \ (-N $ dirname2 \)] Then is executed only when neither dirname1 nor dirname2 is null.
1.3.3. The integer condition shell also provides a arithmetic test set. They compare the numeric values of strings.
-Lt is less
-Le is less than or equal
-EQ equals
-Ge is greater than or equal
-GT greater
-Ne is not equal
2. The forfor loop allows you to repeat a piece of code for a fixed number of times. During loop code execution, a special variable called a loop variable is assigned a different value.
The function of the loop is slightly different.
The for loop is suitable for processing parameters and file sets on the command line. the syntax of the for structure is as follows: for name [in list] dostatementsdonelist is the name list. If the in list is omitted, the default list is "[email protected]", which is the reference list of command line parameters. For example, the content of A. Sh is as follows: For folder in "[email protected]"
Do
Echo-e "\ t $ folder"
Done
The execution result is as follows: $./A. Sh A B C
A
B
C
The echo-e option enables the tab to recognize the escaped formatted characters. Here, it is/T. By the way, the-n option makes echo do not print linefeed at the end.
3. The casecase structure allows you to test strings Based on the pattern that can contain wildcards. In this case, you can more accurately represent a series of if-then-else statements. The syntax of case is as follows: Case expression in pattern1) statements; pattern2) statements; esac any pattern can actually be composed of several modes separated by pipeline characters |, if expression matches one of the modes. The corresponding statement is executed. If several Pipeline character separation modes exist, the expression will try to match each of them so that the corresponding statement is executed. Mode is checked in order until the matching is successful. If none of them match, no action is executed. Note that statements ends with two semicolons. For example, the content of A. Sh is as follows: For filename in "[email protected]"
Do
Case $ filename in
*. Doc | *. docx)
Echo "$ filename: DOC file ";;
*. Txt)
Echo "$ filename: TXT file ";;
*)
Echo "$ filename: Unknown file ";;
Esac
Done
Execution result: $./A. Sh a.txt B .doc c.docx d.pdf
A.txt: TXT file
B .doc: DOC file
C.docx: DOC file
Dashes: Unknown File

4. selectselect allows you to easily generate menus. Syntax: Select name [in list] dostatementsdone is similar to for. You can omit in list, which is "[email protected]" by default, that is, the list of referenced command line parameters, select functions: 1. generate an escape ticket for each target in the list and format it so that each selection corresponds to a number. 2. prompt the user to enter a number. 3. Save the selected entries in the variable name and the selected number in the built-in variable reply. 4. Execute the statements in the entry. 5. Infinite Loop. Chang, for example, A. Sh, which exits the select loop during break, has the following content: PS3 = "directory? "
Select folder in "[email protected]"
Do
Echo "The num is $ reply, $ folder is selected"
Break
Done
Execution result:
$./A. Sh a B c d
1)
2) B
3) c
4) d
Directory? 1
The num is 1, A is selected
5. Syntax of while and untilwhile: While condition test
Do
Execute Command
Done

First, perform a condition test. If the return value is 0 (the condition test is true), the system enters the loop and runs the command area. Otherwise, the system does not enter the loop.

For example, the contents of a. Sh are as follows:

I = 1
While [$ I-le 5];
Do
Echo "$ I"
(I = I + 1 ))
Done

The execution result is as follows:

#./A. Sh
1
2
3
4
5


The until syntax is as follows:

Until condition test
Do
Execute Command
Done

If the condition test result is false (the return value is not 0), it enters the loop.

For example, the contents of a. Sh are as follows:

I = 1
Until [$ I-GT 5];
Do
Echo "$ I"
(I = I + 1 ))
Done

The execution result is as follows:

#./A. Sh
1
2
3
4
5
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.