Shell Programming Trivia

Source: Internet
Author: User

First, the user logged into the system after the system environment variables:
$HOME user's own directory
$PATH the directory that was searched when the command was executed
$TZ Time Zone
$MAILCHECK How many seconds to check if there are new letters
$PS 1 Prompt number at the command column
$PS 2 When the command is not finished, the Shell asks for a prompt to enter again
$MANPATH the search path of the man command

Second, special variables:

The execution name of this program
$n the nth parameter value of this program, n=1..9
$* all parameters of this program
$# the number of parameters for this program
$$ the PID of this program
$! PID that executes the previous instruction
$? Executes the return value of the previous instruction

Third, the shell of the variable element:
* Arbitrary string
? An arbitrary character
[ABC] A, B, c one of the three
[A-n] Any character from A to n

Four, several special character representation

\b Return
\c No line break when printing a line this is what we'll often use.
\f Page Change
\ r Enter
\ t watchmaking
\v Vertical Tabulation
\ \ backslash itself

V. Determining the attributes of a file

Format:-operator filename
-e file exists return 1, otherwise 0 is returned
-R file can be read back 1, otherwise return 0
-W file can write return 1, otherwise return 0
-X file executable returns 1, otherwise 0
-O file belongs to the user himself returns 1, otherwise returns 0
-Z file length of 0 returns 1, otherwise returns 0.
-F File returns 1 for normal file, otherwise returns 0
-D file returns 1 when the directory file is returned, otherwise 0

Six, test string
String 1 = string 2 True when two strings are equal
String 1! = String 2 True when two strings are unequal
-N String True if the length of the string is greater than 0
-Z String True if the length of the string is 0
Strings are true when string strings are non-empty

VII. testing of two integer relationships
Digital 1-EQ number 22 number equal to True
Digital 1-ne Number 22 number is true
Digital 1-GT number 2 digit 1 greater than the number 2 is true
Digital 1-ge Digit 2 number 1 is greater than or equal to the number 2 is true
Digital 1-LT digit 2 digit 1 less than the number 2 is true
Digital 1-le Digit 2 number 1 is less than or equal to the number 2 is true

Eight, logic test
-A and
-O or
! Non -

Today's reference to shell special characters
===============================
Special characters in the Shell have

1, $ dollar symbol
2, \ anti-slash
3, ' anti-quote
4, "double quotes
5, <, >,*,?, [,]

I'll make a list of the following
A, $ symbol
1, echo $? Shows the previous instruction exit status
2, echo "$?" Effect ditto
3, Echo ' $? ' shows the $?
4, Echo \$? Is it displayed in $?
5, echo "\$?" Display is $?

You may have seen the $ sign in double quotes with a special meaning double quotation marks do not work with the $ symbol
Single quotation marks can be used to Fu the special meaning of special words, so that they can be displayed as the character itself, reverse oblique
The bar can also be special characters of the special meaning of shielding off, so that special characters lose special meaning.

Two, \ anti-slash
The effect of a backslash is to mask the special meaning of a special symbol character, so that it is still the original character
a=1234
echo \ $A shown as $ A if not plus \ will be displayed as 1234
echo \ ' Display as '
echo \ "Display as double quotation marks
echo \ \ is displayed as \

Three, ' anti-quote
The function of anti-quotation marks is command substitution, the string in the anti-quotation mark as a command to execute, we use the shell programming often to the execution of the system command to assign a variable

A= ' Date '
Echo $A doesn't show date but time string.
For example, the contents of a file A are as follows
ABCDEFG
1234456
Abcdefg

B= ' cat A|grep 234 '? # Retrieve the line containing the string 234 in file a
The Echo $B will be displayed as 1234456
echo "$B" will show why?
echo "\ $B" will show why? Readers try it Yourself

Four, "double quotes
There are special characters in the system that are often enclosed in double or single quotes to avoid referencing these special characters so that they do not have special meanings.
However, some special characters have special meanings in quotation marks, and it is not useful to enclose them in double quotation marks. The first four special characters listed in this article are still special characters in double quotation marks. In order to make it do not have a special meaning one is to use a single quotation mark to the second is to use the \ backslash to make it lose effect.

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

echo "" "
echo "$"
echo "\"
echo "'"
These are not the results you expect, because double quotes do not work for them, and you can only do so in order to output these special characters.
Echo ' "'
Echo ' $ '
echo ' \ '
echo "
Or
echo "\" "
echo "\$"
echo "\ \"
echo "\"
will be displayed separately as "$ \"
V. Other special characters
It is noted that except for the first four special characters I put the other special characters in one piece, because the first four special characters in double quotation marks or have special meanings, so separate out in terms of other special characters if you want to output these special characters of the prototype, You can use double or single quotation marks to cause it to lose its special meaning.
<, >,*,?, [,] have a special meaning for the shell but you can use double quotes to enter these prototypes.

So many people have noticed that all the special characters in single quotes lose special meaning, if you want to output special characters in the original form but also do not remember those special characters in double quotation marks can not output prototype, we suggest you simply enclose in single quotation marks.

Introduce conditional test statements today

One, if condition statement
Format:
An IF condition expression
Then #当条件为真时执行以下语句
Command List
else #为假时执行以下语句
Command List
Fi

If statements can also be nested using

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 do multiple layers of nesting an if statement must be followed by a fi representation that the layer condition ends otherwise it will cause a syntax error
In conjunction with the preceding example, the following are:
Here, let's start with the command test used in a conditional statement to indicate whether the condition after test tests is true

If Test-f "$"
Then
LPR $
Else
If test-d "$"
Then
CD $
LPR $
Else
echo "$ not a file or directory"
Fi
Fi

The above example can also be changed to the following

If Test-f "$"
Then
LPR $
Elif test-d "$" #elif with else if
Then
(CD $1;LPR $)
Else
echo "$ not a file or directory"
Fi??????

The above example does not know whether you understand what is the meaning of it?
If we now save this example as Prfile
chmod +x Prfile
Execute the procedure just now.
./prfile AAA

This example is to check if your input parameter is a file if it is printed if it is a directory to go to the directory before printing if it is not a file is not a directory to give a hint

Second, multiple conditions test statement case
Format:
Case string in
mode) command list;;
mode) command list;;
....
Esac

Multiple conditional statements are started in case with ESAC end can have more than one condition list function is the test string and the pattern inside and there is no match, there is a command list inside the pattern can also be * number denotes any string, each pattern inside the final heart; The double quotation mark ends, or a syntax error occurs.

Examples are as follows:

Case $ in
*.C)
CC $
;;
*.txt)
LPR $
;;
*)
echo "Unknown type"
Esac

If you save the above content in the file ABC

chmod +x ABC
Execute./ABC A.C will compile the file a.c
Execute./ABC Readme.txt will pass the file through the printer
If I change the above content, will you know the result of its execution?

Case $ in
*)
CC $
;;
*.txt)
LPR $
;;
*.C)
echo "Unknown type"
Esac

Introduce the Loop statement today
A. While loop
While command format

While condition table
Do
Command table
Done

Execution process

The shell executes the condition table first, and if the last statement of the condition table has an exit state of zero, the command inside the Shield ring is executed
Table, after execution, then check the condition table, if the exit status is zero will continue to execute, and so on until the condition table
The exit status of the last statement is not 0. An exit status of zero is true if the condition is true.

For example, if the contents of the shell file are as follows:

Sum=0
I=0
While True #true是系统的关键词 represents true
Do
i= ' expr $i + 1 '
sum= ' expr $Sum + $i '
if [$i = "100"]
Then
Break
Fi
Done
echo $i $Sum
Finally, this program shows 100 5050.
The operation of this program is to add 1 to 100.

Let's change the program a little bit later.



Sum=0
I=0
while [$i! = "100"]
Do
i= ' expr $i + 1 '
sum= ' expr $Sum + $i '
Done
echo $i $Sum

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

In this loop, you can also use until as the test condition, which is the opposite of the condition of the while test, that is, when the condition is false will continue to execute the Loop body statement, or exit the loop body, the following also used this example.


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 the loop when the condition is false, otherwise it exits, and the first example is when I is not equal to 100
Loop when the test condition is true.

Two. For loop

Command format:
For variable in name list
Do
Command List
Done

The list of names here is a space-delimited list of strings, each time the shell executes a for loop, sequentially from the name table
Takes a string assigned to the loop variable as the value of the variable.
When writing a for statement, you can also omit the In Name list section, which means that the current position parameter is used instead of the name
Word list.
Here's an example.
For example, there are two directories in your computer, one is AA, the other is BB has 5 identical files in both directories, but its
One or more of the files in a directory has just been modified, and now I forget to change the number of files, then I * Officer Shing Whirl supervised reef Guoco jealous Nai, the application of the Oval lazy program is as follows:

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

Here's another example without a list of names.

For File
Do
Echo $FILW
Done

The contents of the file are saved in a.sh and can be executed
The command line when we execute this shell program is as follows:
A.SH A1 A2 A3 A4 A5
The results of the implementation are as follows:
A1
A2
A3
A4
A5
As you can see from this example, the command line parameters are read one at a time.
Three. Circular control statements
The break command does not perform the current loop within the body of a break, and the following statement exits from the current loop.
The Continue command is a program that ignores the following statement in this body and executes from the loop header.

One, command combination: parentheses and braces
There are two ways to group commands together in the shell: parentheses and braces. Parentheses enables the shell to create a child shell
To read and execute the enclosed name command. The shell will be in the left and right brackets regardless of where it appears on the command line.
Think they have a special combination of meanings. Parentheses or curly braces are only represented by enclosing them in double quotation marks
of the original meaning. For example:

echo A (b)
There will be a syntax error in order for the output A (b) string to be enclosed only.
echo "A (b)"
or echo a "(" B ")"
This can be interpreted correctly by the shell.
What does it do with a combination command?
One, use parentheses to combine commands
The combination of parentheses command can create a sub-process to run the composition program, it is useful to establish the function of the child process, because
The various operations of the child shell in the combo command do not affect the values of the variables of the current shell.
For example:
The child process changes the working directory when it executes the composite command, executes a line of command under the new working directory, and executes
It does not have to return to the original working directory, because the changes to the working directory of the child process do not affect the current working directory.

After the child process is created, the current environment is also passed to the child shell, and the current shell is exported to the environment using export
The variables are equally valid in the child shell.


Curly braces can also combine commands. Left and right curly braces only appear as the first word of a command,
The shell only has special meanings.
Unlike parentheses, curly braces do not create child shells, only the current shell reads and executes the enclosed
command. Sometimes the user wants to use the order of a set of commands to output the input as another set of commands, with curly braces
The.
The exit State is equal to the exit state of the last command enclosed, whether the parentheses are not curly brackets.


Second, commands that can be executed in the current shell

Users must be aware of the commands that can be executed in the current shell when using the shell, which cannot be
The commands that can be executed in the current shell are:

Break Case CD Continue
echo Eval exec exit
Export for if read
ReadOnly return set shift
Test times Trap Umask
Until wait while
: {}

Shell Programming Trivia

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.