Linux main shell commands in detail (medium)

Source: Internet
Author: User
Tags echo command sorts

Special characters in the shell

In addition to using ordinary characters in the shell, you can use special characters that have special meanings and functions. They should be used with special meaning and scope of action. Each of these special characters is described below.

1. Wildcard characters

Wildcard characters are used for pattern matching, such as file name matching, path name search, string lookup, and so on. Common wildcard characters have *,?, and character sequences enclosed in square brackets []. The user can include these wildcard characters in the file name as a command parameter, forming a so-called "pattern string" that performs pattern matching during execution.

* represents any string (length can vary), for example: "f*" matches any string preceded by F. It should be noted, however, that the dot (.) before the file name and the slash (/) in the path name must be explicitly matched. For example, "*" does not match. File, and ". *" can match. File.

? Represents any single character.

[] represents a specified range of characters, as long as the character at [] position in the file name is within the range specified in [], then the file name matches the pattern string. The range of characters in square brackets can consist of directly given characters, or it can consist of the starting character, the terminating character, and the middle hyphen (-) representing the qualifying range. For example, F [a-d] has the same effect as f [ABCD]. The shell will take all filenames that match the pattern string specified in the command line as arguments to the command, forming the final command, and then executing the command.

Below we give the specific meanings of these wildcard characters in table 10-1.

Table 10-1 Examples of wildcard meanings

Pattern string

Significance

*

The name of all the files in the current directory.

*text*

The name of the file in the current directory that contains text in all file names.

[ab-dm]*

The names of all files in the current directory that begin with a, B, C, D, M.

[AB-DM]?

The name of all files in the current directory that begin with a, B, C, D, M, followed by only one character.

/usr/bin/??

The name of all files with a name of two characters under directory/usr/bin.

 

It is particularly important to note that the hyphen "-" is only valid within square brackets, and represents a range of characters, such as a normal character outside the square brackets. and * and? Only outside the square brackets are wildcards, and if they appear inside square brackets, they also lose their ability to become ordinary characters. For example, only one square bracket in the pattern "-A[*?]ABC" is a wildcard character, * and? are ordinary characters, so it can only match the string-a*abc and-a?abc.

Finally, explain some of the issues that you need to be aware of when using wildcard characters. Because *,?, and [] have a special meaning for the shell, these characters should not appear in the normal file name. In particular, do not appear in the directory name, otherwise the shell may be infinitely recursive. Another thing to note is that if the directory does not have a file name that matches the specified pattern string, the shell uses the pattern string itself as an argument to the command. This may be the reason why the special characters appear in the command.
2. Quotation marks

There are three types of quotes in the shell: single quotes, double quotes, and anti-quotes.

* Single quote '

The character nonalphanumeric enclosed by single quotation marks appears as normal characters. When special characters are enclosed in single quotes, they lose their original meaning and are interpreted only as ordinary characters. For example:

$ String= ' $PATH '

$ echo $string

$PATH

$

Visible $ maintains its own meaning, appearing as ordinary characters.

* Double Quotes "

Characters enclosed in double quotation marks, except $,, ', and ' are still special characters and retain their special functions, remaining characters are treated as ordinary characters. For $, the variable and $ are replaced by the value of the variable specified later, and for the purpose of the escape character, it tells the shell not to treat the character that follows it with special handling, just as a normal character. As you can imagine, in double quotes you need to add only four characters in front of $,, ' and ' itself. In the case of the "number", the shell will match it with the previous "number if it is not preceded by an addition.

For example, we assume that the value of path is.:/ Usr/bin:/bin, enter the following command:

$ teststring= "$PATH \" $PATH "

$ echo $TestString

.:/ usr/bin:/bin "$PATH

$

The reader can try it out on its own before the second double quotation mark does not add any results.

 

* Anti-quote '

The inverse quotation mark (') corresponds to the key in the upper-left corner of the keyboard, and do not confuse it with single quotation marks ('). The string that is enclosed in quotation marks is interpreted by the shell as the command line, and at execution time, the shell executes the command line first and replaces the entire anti-quotation mark (including two anti-quote) portions with its standard output results. For example:

$ pwd

/home/xyz

$ string= "current directory is ' pwd '"

$ echo $string

Current Directour is/home/xyz

$

When the shell executes the echo command, it first executes the command pwd in ' pwd ' and outputs the result/home/xyz instead of ' pwd ', and outputs the entire result after the replacement.

This function of anti-quote can be used for command substitution, that is, the execution result of the inverted quotation marks is assigned to the specified variable. For example:

$ Today= ' Date '

$ echo Today is $today

Today is Mon Apr 16:20:13 CST 1999

$

Anti-quotes can also be nested. It is important to note, however, that the inner layer's back quotation marks must be escaped with a backslash () when nested. For example:

$ Abc= ' echo the number of users is ' who| Wc-l "

$ echo $ABC

The number of users is 5

$

Special characters from the shell can also be used in the command line between the anti-quotes. The shell is actually going to execute the specified command in order to get the result of the command in. When executed, the special characters in the command, such as $, ",? And so on, will have a special meaning, and ' can contain any valid shell command, such as:

$ ls

Note Readme.txt Notice Unix.dir

$ teststring= "' echo $HOME ' ls [nn]* ']

$ echo $TestString

/HOME/YXZ Note Notice

$

In other cases, the reader can try it out on its own.

1. Annotation characters

Some body lines are often commented on in shell programming to increase the readability of the program. The body line that begins with the character "#" in the shell represents the comment line.

There are also special characters such as: <, >, <<, >> and | For input/output redirection and piping, &; command execution operators && and | | and {}, which represents the command group, are described in the following subsections.
Standard input/output and redirection

1. Standard input and output

We know that executing a shell command line typically automatically opens three standard files, the standard input file (stdin), which usually corresponds to the terminal's keyboard, the standard output file (stdout), and the standard error output file (stderr), which correspond to the screen of the terminal. The process will get input data from the standard input file, output normal output data to the standard output file, and send the error message to the standard error file.

We take the cat command as an example, the function of the Cat command is to read the data from a file given at the command line and send the data directly to the standard output. If you use the following command:

$ cat Config

The contents of the file config will be displayed to the screen in turn. However, if there are no parameters in the cat's command line, it reads the data from the standard input and sends it to the standard output. For example:

$ cat

Hello World

Hello World

Bye

Bye

$

Each line entered by the user is immediately output to the screen by the cat command.

In another example, the command sort reads into the body of the file by line (when the file name is not given in the command line, it reads from the standard input), sorts it, and sends the result to standard output. The following example reads a purchase order from the standard input and sorts it.

$ sort

Bananas

Carrots

Apples

Apples

Bananas

Carrots

$

At this point we got a sorted purchase order on the screen.

The following issues exist with the direct use of standard input/output files:

Input data from the terminal input, the user costs a half-day input data can only be used once. The next time you want to use this data, you have to re-enter it. And in the terminal input, if the input is wrong to modify it is not very convenient.

The information output to the terminal screen can only be viewed as not moving. We cannot do more with this output, such as further processing of the output as input to another command.

To solve these problems, the Linux system introduces two other mechanisms, input/output redirection and pipeline, for input and output transmission.

2. Input redirection

Input redirection refers to redirecting the standard input of a command (or executable program) to a specified file. That is, the input may not come from the keyboard, but from a specified file. So, input redirection is primarily used to change the input source of a command, especially to change input sources that require a lot of input.

For example, the command WC statistic specifies the number of rows, words, and characters that the file contains. If you type only on the command line:

$ WC

The WC waits for the user to tell it what to count, and then the shell seems to be dead, all the text typed from the keyboard appears on the screen, but nothing happens until the is pressed, and the WC writes the command result on the screen.

If you give a filename as a parameter to the WC command, as the following example shows, the WC returns the number of rows, words, and characters that the file contains.

$ wc/etc/passwd

726/etc/passwd

$

Another way to pass the contents of the/etc/passwd file to the WC command is to redirect the input of the WC. The general form of input redirection is: Command < file name. You can redirect the input of the WC command to the/etc/passwd file using the following command:

$ WC </etc/passwd

20 23 726

$

Another type of input redirection, called the here Document, tells the shell that the standard input for the current command is from the command line. The redirect operator for the here document uses <<. It converts the body of a pair of delimiters (in this case, denoted by Delim) to the command. The following example takes the body of a pair of delimiter delim as input to the WC command, counting the number of lines, words, and characters of the body.

$ wc<

>this Text forms the content

>of the Here Document,which

>continues until the end of

>text Delimter

>delim

4 17 98

After the << operator, any character can be used as a delimiter before the beginning of the body, in this case using Delim as the delimiter. The body of the here document continues until you meet another delimiter. The second delimiter should appear at the beginning of the new line. The body of the here document (excluding the start and end separators) is redirected to the command WC as its standard input.

Because most commands specify the file name of the input file on the command line as a parameter, input redirection is not often used. However, when you want to use a command that does not accept the file name as an input parameter, and the required input is in a file, you can resolve the problem with input redirection.

1. Output redirection

Output redirection refers to redirecting the standard output or standard error output of a command (or executable program) to a specified file. In this way, the output of the command is not displayed on the screen, but is written to the specified file.

Output redirection is more common than input redirection, which can be used in many cases. For example, if a command has a lot of output and cannot be fully displayed on the screen, redirect the output to a file and then open the file with a text editor to view the output information, or you can use this method if you want to save the output of a command. Also, output redirection can be used to take the output of one command as input to another command (there is also an easier way to use the pipeline, as described below).

The general form of output redirection is: command > File name. For example:

$ ls > directory.out

$ cat Directory.out

Ch1.doc ch2.doc Ch3.doc Chimp config mail/test/

$

Save the output of the LS command as a file named Directory.out.

Note: If the file behind the > symbol already exists, then this file will be rewritten.

To avoid the output redirection of the current command, the shell provides an additional means of output redirection in order to prevent the specified file from being redirected. Output append redirection is very similar to output redirection, except that the function of the output append redirection is to append the output of the command (or executable program) to the end of the specified file, and the original content of the file is not destroyed.

If you want to append the output of a command to the specified file, you can use the Append redirect operator >>. The form is: command >> file name. For example:

$ ls *.doc>>directory.out

$ cat Directory.out

Ch1.doc ch2.doc Ch3.doc Chimp config mail/test/

Ch1.doc Ch2.doc Ch3.doc

$

As with the standard output redirection of the program, the error output of the program can also be redirected. Use symbol 2> (or append symbol 2>>) to indicate error output device redirection. For example, the following command:

$ ls/usr/tmp 2> Err.file

The normal output of the program can be seen on the screen, but any error messages from the program are sent to the file err.file for future inspection.

You can also use another output redirection operator (&>) to send both standard output and error output to the same file. For example:

$ ls/usr/tmp &> Output.file

By combining commands with redirects, you can implement new features that the system cannot provide with a single command. For example, use the following sequence of commands:

$ ls/usr/bin >/tmp/dir

$ wc–w </tmp/dir

459

The number of files in the/usr/bin directory is counted.

Pipeline

The output of one program or command as input to another program or command, one of two ways is to combine two commands or programs with a temporary file, such as the/tmp/dir file in the previous example, to associate LS with the WC command, and the pipeline functionality provided by Linux. This method is better than the previous method.

A pipeline can connect a series of commands, which means that the output of the first command is passed to the second command as input to the second command, and the output of the second command is then entered as the third command, and so on. The display on the screen is the output of the last command in the pipe line (if output redirection is not used in the command line).

By using the pipe symbol ' | ' To create a pipe line. Use the pipeline to rewrite the example above:

$ ls/usr/bin|wc-w

1789

Again such as:

$ cat Sample.txt|grep "High" |wc-l

The pipeline sends the output of the Cat command (which lists the contents of a file) to the grep command. The grep command finds the word in the input the output of the High,grep command is all lines that contain the word high, and the output is sent to the WC command, which counts the number of rows in the input. Suppose the contents of the Sample.txt file are as follows:

Things to do today:

Low:go Grocery Shopping

High:return Movie

High:clear level 3 in Alien vs. Predator

Medium:pick up clothes from dry cleaner

Then the result of the pipeline line is 2.

Command substitution

Command substitution and redirection are somewhat similar, but the difference is that command substitution is the output of one command as a parameter to another command. Common command formats are:

Command1 ' Command2 '

Where the output of the Command2 will be used as the Command1 parameter. It is important to note that the ' symbol ', the contents of which it is enclosed, will be executed as a command, and the result as a Command1 parameter. For example:

$ cd ' pwd '

The command lists the directories listed by the PWD command as parameters to the CD command, and the result remains in the current directory.

22nd operation in Bash 2000 years/May/29th

Command and file name extension attributes

The bash command line has command and file name extension attributes. When entering a command or file name that has not yet been completed, simply type the TAB key to activate the command and filename extension to complete the remaining input of the command. If there are multiple commands or files with the same prefix, bash will ring and wait for the user to enter enough characters to select a unique command or file name, and if found, the system will automatically fill in the search to the command or file name, after the user presses ENTER, the system will execute this instruction. For example:

$ cat Pre

$ cat Preface

Bash can also list file names that are partially matched under the current directory to complete the filename extension. If you type ESC, and then type?, the shell lists all the file names that match the input string. For example, after an input that has not been completed, type Esc?,shell to list all strings that match the input string, and then the shell echoes the command line, depending on the file name listed, you can type the file name you want to enter or press the TAB key to complete the filename extension. For example:

$ ls

Document Docudrama

$ cat Doc

Document

docudrama

$ cat docudrama

[Example] The following is a list of files that a directory contains:

Firebird2.7.tgz Firebird.readme firebird2.60.tgz

FireBird Firebird2.60.tgz.readme

Now to delete the Firebird2.60.tgz.readme file, type:

$ rm–f Fi

The system emits an alert and automatically complements the command line:

$ rm–f Fire

And wait for the user to further enter the later part of the file name. Now type again:

B

The system beeps again and automatically complements the command line as follows:

$ rm–f Firebird

And wait for the user to further enter the later part of the file name. Now type again:

2.6

The system beeps again and automatically complements the command line as follows:

$ rm–f firebird2.60.tgz

And wait for the user to further enter the later part of the file name. Now type again:

.

At this point the command will be complete as follows:

$ rm–f firebird2.60.tgz. Readme

As you can see from the previous example, Bash always tries to fill in the commands according to the information entered by the user. When the command cannot be complete according to the existing information, the user is prompted to give more information, and then follow the user's prompts to further complete the command. As a user it is best to be able to give enough information at once to make the command completion in bash, otherwise press more times and the time is consumed.

Command line editing

You can edit the command line in bash so that users can modify the commands they type before they execute the command you type. If you have a spelling error typing a command, simply use the edit command to correct the edit error before you run the command you typed, and then execute it without re-entering the entire line of commands. This feature is especially useful for commands with long path file parameters.

Table 10-2 is a summary of the command-line editing operations.

Table 10-2 Command-line editing operations

Linux main shell commands in detail (medium)

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.