Several shell programming tips (shell knowledge)

Source: Internet
Author: User

[From] http://blog.chinaunix.net/uid-168249-id-2860686.html

Reference: 1. system environment variables after a user logs on to the system:
$ Home user's own directory
$ Path: the directory to be searched during Command Execution
$ TZ Time Zone
$ Mailcheck the number of seconds to check whether a new letter exists
$ PS1 prompt number in the Command Column
$ PS2 indicates the prompt number when shell requests to re-input when the command has not been completed
$ Manpath man command search path

Ii. Special variables:

$0 execution name of the program
$ N the nth parameter value of this program, n = 1 .. 9
$ * All parameters of this program
$ # Number of parameters of this program
$ PID of the program
$! PID used to execute the previous command
$? The Return Value of the previous command.

3. Variable in shell:
* Any string
? Any character
[ABC] One of the three: A, B, and C
[A-N] any character from A to N

4. Special characters

\ B Return
\ C is often used to print a row without line breaks.
\ F form feed
\ R press ENTER
\ T tabulation
\ V vertical tabulation
\ Backslash itself

V. Determining file attributes

Format:-operator filename
-If the file-e exists, 1 is returned; otherwise, 0 is returned.
-If the r file is readable, 1 is returned; otherwise, 0 is returned.
-W file write return 1, otherwise return 0
-1 is returned for executable-X Files; otherwise, 0 is returned.
-O: if the file belongs to the user, 1 is returned; otherwise, 0 is returned.
-If the length of the Z file is 0, 1 is returned; otherwise, 0 is returned.
-If the f file is a normal file, 1 is returned; otherwise, 0 is returned.
-If the D file is a directory file, 1 is returned; otherwise, 0 is returned.

6. Test the string
String 1 = string 2 true when two strings are equal
String 1! = String 2: true when two strings are not equal
-N string: true when the string length is greater than 0
-Z string: true when the string length is 0
String is true when the string is not empty

7. Test the relationship between two integers
Number 1-EQ Number 2 equal to true
The number 1-ne number 2 is not true.
Digit 1-GT digit 2 digit 1 greater than digit 2 true
Number 1-ge number 2 Number 1 greater than or equal to number 2 true
Number 1-lt number 2 Number 1 less than number 2 true
Number 1-Le number 2 Number 1 less than or equal to number 2 true

8. Logic Testing
-A and
-O or
! Non



Introduction to shell special characters
====================================
Special characters in Shell include:

1. $ dollar sign
2. \ backslash
3. 'quotation marks
4. Double quotation marks
5. <,> ,*,?, [,]

The following is a one-to-one description.
1. $ symbol
1. Echo $? Displays the exit status of the previous command.
2. Echo "$? "Same effect
3. Echo '$? 'Is $?
4. Echo \ $? $?
5. Echo "\ $? "Show $?

You may have seen that the $ symbol has a special meaning in double quotation marks. Double quotation marks do not work for the $ symbol.
The single quotation marks can block the special meanings of special characters so that they can be displayed as characters themselves.
The bar can also block the special meanings of special characters, so that special characters do not have special meanings.

Ii. \ backslash
The backslash is used to block the special meaning of a special character so that it is the original character.
A = 1234
Echo \ $ A is displayed as $ A. If no value is added, 1234 is displayed.
Echo \ 'displayed'
Echo \ "is displayed as double quotation marks
Echo \ is displayed \

Iii. 'quotation marks
The function of anti-quotation marks is to replace commands and execute strings in the anti-quotation marks as commands. We often use shell programming to assign the execution result of system commands to a variable.

A = 'date'
Echo $ A shows the time string instead of the date.
For example, the content of file a is as follows:
Abcdefg
1234456
Abcdefg

B = 'cat A | grep 234 '? # Retrieve the row containing string 234 in file
Echo $ B is displayed as 1234456
Echo "$ B" will show why?
Echo "\ $ B" will show why? Try it by yourself

Iv. Double quotation marks
There are some special characters in the system. To avoid referencing these special characters, these special characters are often caused by double quotation marks or single quotation marks, so that they do not have special meanings.
However, some special characters still have special meanings in quotation marks, which are caused by double quotation marks and do not work. The first four special characters listed in this article are in double quotation marks or special characters. In order to make it have no special meaning, one is to use single quotation marks, and the other is to use \ backslash to make it useless.

For example, we want to output these special characters as they are.

Echo """
Echo "$"
Echo "\"
Echo "'"
The above is not the expected result, because double quotation marks do not work for them, you can only output the prototype of these special characters
Echo '"'
Echo '$'
Echo '\'
Echo '''
Or
Echo "\""
Echo "\ $"
Echo "\\"
Echo "\'"
It is displayed as "$ \'
5. Other special characters
We noticed that except the first four special characters, I put all the other special characters in one piece. This is because the first four special characters still have special meanings in double quotation marks, so I will explain them separately, if you want to output the prototype of these special characters, you can use double quotation marks or single quotation marks to make them lose their special meaning.
<,> ,*,?, [,] It has a special meaning for shell, but you can use double quotation marks to input these prototypes.

Have you noticed that all special characters have no special meaning in single quotes? If you want to output the original form of special characters but cannot remember that these special characters cannot output the original form in double quotes, we recommend that you use single quotes.

Introduction to conditional test statements today

I. If condition statements
Format:
If condition expression
Then # execute the following statement when the condition is true
Command list
Else # execute the following statement when false
Command list
Fi

If statements can also be nested

If condition expression 1
Then
If condition expression 2
Then
Command list
Else
If condition expression 3
Then
Command list
Else
Command list
Fi
Fi
Else
Command list
Fi

You can perform multi-layer nesting. An if statement must end with a fi to indicate the condition of the layer. Otherwise, syntax errors may occur.
The following are examples:
Here we first talk about the command test used in a condition statement to test whether the condition after test is true.

If test-F "$1"
Then
LPR $1
Else
If test-d "$1"
Then
CD $1
LPR $1
Else
Echo "$1 is not a file or directory"
Fi
Fi

The above example can also be changed to the following:

If test-F "$1"
Then
LPR $1
Elif test-d "$1" # Elif is the same as else if
Then
(CD $1; LPR $1)
Else
Echo "$1 is not a file or directory"
FI ??????

Do you understand the above examples?
If we save this example as prfile
Chmod + x prfile
Execute the program
./Prfile aaa

In this example, check whether your input parameter is a file. If it is a file, print it. If it is a directory, convert it to a directory and then print it. If it is not a file or a directory, a prompt is given.

Ii. Multi-condition test statement case
Format:
Case string in
Mode) command list ;;
Mode) command list ;;
....
Esac

The multi-Condition Statement starts from case and ends with esac. Multiple condition lists can be used to test whether the string matches the pattern in it, the command list mode in execution can also be "*" to represent any string, and the last point in each mode is the heart; double quotation marks are used to end; otherwise, a syntax error occurs.

The following is an example:

Case $1 in
*. C)
CC $1
;;
*. Txt)
LPR $1
;;
*)
Echo "unknown type"
Esac

If you save the preceding content in the ABC file

Chmod + x ABC
Execute./abc a. C to compile the file a. c.
Execute./ABC readme.txt and the file will be passed through the printer
If I change the preceding content, do you know the execution result?

Case $1 in
*)
CC $1
;;
*. Txt)
LPR $1
;;
*. C)
Echo "unknown type"
Esac

Today we will introduce loop statements
1. While Loop
While Command Format

While condition table
Do
Command table
Done

Execution Process

Shell first executes the condition table. If the exit status of the last statement in the condition table is zero, execute the commands in the environment
After the execution, check the condition table. If the exit status is zero, the execution continues until the condition table's
The exit status of the last statement is non-zero. If the exit status is zero, the condition is true.

For example, if the content of the shell file is as follows:

Sum = 0
I = 0
While true # True is the system keyword indicating true
Do
I = 'expr $ I + 1'
Sum = 'expr $ sum + $ I'
If [$ I = "100"]
Then
Break;
Fi
Done
Echo $ I $ sum
The program shows 100 5050
The calculation of this program is to add 1 to 100

Next, let's change this program.


Sum = 0
I = 0
While [$ I! = "100"]
Do
I = 'expr $ I + 1'
Sum = 'expr $ sum + $ I'
Done
Echo $ I $ sum

The modified program operation result is the same as above, but the program is more concise than above.

In this loop, you can also use until as the test condition. It is exactly the opposite of the while test condition, that is, when the condition is false, the statement in the loop will continue to be executed, otherwise, exit the loop body. This example is also used below.


Sum = 0
I = 0
Until [$ I = "100"]
Do
I = 'expr $ I + 1'
Sum = 'expr $ sum + $ I'
Done
Echo $ I $ sum
When I is not equal to 100, the loop is when the condition is false. Otherwise, the loop exits. The first example is when I is not equal to 100.
Cycle, that is, when the test condition is true.

II. For Loop

Command Format:
For variable in Name List
Do
Command list
Done

The name list here is a list of strings separated by spaces. Shell runs the for loop from the name table
Take a string and assign it to the cyclic variable as the variable value.
When writing a for statement, you can also omit the in name list section, which means that the current location parameter is used to replace the name
Word List.
The following is an example.
For example, there are two directories in your computer, one is AA, and the other is BB. There are five identical files in these two directories, but their
One or more files in one directory have just been modified. Now I forget the files I just modified, so I am relying on the reseller to raise a fund for Ke yunnai, the reef in the xianxian region? Elliptical? Lazy? The procedure is as follows:

For file in A1 A2 A3 A4 A5
Do
Diff AA/$ file bb/$ File
Done

The following is an example without a name list.

For file
Do
Echo $ filw
Done

The file content is saved in A. SH and can be executed
When we execute this shell program, the command line is as follows:
A. Sh A1 A2 A3 A4 A5
The execution result is as follows:
A1
A2
A3
A4
A5
In this example, we can see that the command line parameters are read one by one.
Iii. Loop Control statements
The break command does not execute the statements in the current cycle following the break.
The continue command is used by the program to ignore the following statements in the current cycle and start execution from the loop header.

I. Command combination: parentheses and curly braces
There are two methods in shell to combine commands: parentheses and curly brackets. Parentheses enable shell to create a subshell
To read and execute the enclosed name command. No matter where the left and right brackets appear in the command line, shell will
They have special meanings in combination. They are enclosed and referenced in double quotation marks to indicate parentheses or curly braces.
For example:

Echo A (B)
Syntax errors may occur. to output A (B) strings, you must enclose them.
Echo "A (B )"
Or echo a "(" B ")"
In this way, it can be correctly explained by shell.
What is the function of using combined commands?
I. use parentheses to combine commands
The combination command of parentheses can create sub-processes to run the combined program. It is useful to create sub-processes because
All the operations of the sub-shell in the Combined Command do not affect the values of various variables of the current shell.
For example:
The sub-process changes the working directory when executing the combined command, and runs a series of commands in the new working directory.
After completion, it does not have to return to the original working directory, because the change of the sub-process working directory does not affect the current working directory.

After the sub-process is created, the current environment is also passed to the sub-shell, and export is used in the current shell to output to the environment
Each variable is also valid in the subshell.


The curly braces can also be used to combine commands. The left and right curly braces only appear as the first word of a command,
Shell.
Unlike parentheses, curly braces do not create subshells, but are read and executed by the current shell.
Command. Sometimes you want to use the sequential output of a group of commands as the input of another group of commands. In this case, the curly brackets are very square.
Convenient.
Whether the parentheses are used or not, the exit status is equal to the exit status of the last enclosed command.


2. commands that can be executed in the Current Shell

When using shell, you must understand the commands that can be executed in the current shell.
The following commands can be executed in the current shell:

Break case CD continue
Echo eval exec exit
Export for if read
Readonly return set shift
Test times trap umask
Until wait while
:{}

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.