BASH Shell (5)-data stream redirection

Source: Internet
Author: User

Data Stream redirection refers to the data that should appear on the screen after a command is executed and transmitted to another place, such as a file or device (such as a printer !)! This is important in Linux text mode! This is especially useful when we want to store some data!

Generally, if you want to execute a command, it will usually be like this:

When we execute an instruction, the instruction may read data from the file and output the data to the screen after processing. In the figure, standard output and standard error indicate standard output and standard error output respectively. Both of them are output to the screen by default! For example, when we issue the "cat/etc/crontab/etc/vbirdsay" command, cat reads data from/etc/crontab and/etc/vbirdsay, then output the data to the screen. However, because the system does not have the/etc/vbirdsay file, an error message is displayed, this error message will also be output to the screen! In this process, we can send standard error (stderr) and standard output (stdout) to another place, rather than the head of the screen! The destination of the transfer, usually an archive or device! The sent command is as follows:

1. Standard input (stdin): the code is 0, use <or <;
2. standard output (stdout): the code is 1, use> or>;
3. Standard Error output (stderr): Code 2, Use 2> or 2>;

For example, if I want to record all the directories under my current root directory, that is, save the output results of the LS-L/command:

[Root @ Linux ~] # Ls-L/> ~ /Rootfile

# Originally, LS-L/will list the data in the root directory to the screen;
# I have used it now> ~ /Rootfile, the data that should have appeared on the screen
# It will be "redirected" ~ /The rootfile file is in! You can store the data!

At this point, the data that should have appeared on the screen is invisible ~ Because all the materials are written ~ /Rootfile is gone! Of course, you can choose the file name for that file ~ If you issue: "cat ~ /Rootfile "to view the data on the screen. Then, if I try again: "ls-L/Home> ~ /Rootfile, then ~ /What is the content of the rootfile file? Haha! It becomes "only LS-L/home data! Success! Will the original LS-L/Data disappear? Yes! Because the file is created in the following way:

1. This file (in this example, It is ~ /Rootfile) if the file does not exist, the system automatically creates the file. However,
2. When this file exists, the system first clears the file content and then writes the data!
3. That is, if the file is output to a stored disk, the file will be overwritten!

ThatIf I want to accumulate and not delete old data, what should I do? Haha! Use it>That's all! For example, in the above example, it is changed to "ls-L/> ~ /Rootfile "As a result, when ~ /When the rootfile does not exist, the system will create the file. If the file already exists, the data will be accumulated at the bottom of the file! Basically, instructions are issued in the following way:

Command> 1> 2> 2> <device or file

Of course, the leftmost part of a string of commands must be commands. In>, 2>, <the rightmost part must be files or devices! In addition, that> will be equal to 1>, because the standard output code is 1, you can omit it! Furthermore, there is no space between 1 and>! It's coming together! Note! Let's have a few things:

Example 1: store all the file information in the current directory to the list.txt file.
[Root @ Linux ~] # Ls-Al> list.txt

Example 2: store the data in the root directory to the list.txt file.
[Root @ Linux ~] # Ls-Al/> list.txt

Now that we have some concepts about ">>>>", let's talk about the concept of "data stream redirection" in depth! As mentioned above, basically, the results of Linux execution can be roughly divided into two types of data: "correct output" and "error output. For example, when you execute the "Find/-name testing" command as a general identity, some data folders do not allow normal identities to access, so when you use find, an error message will occur! But if there is a file named testing in the folder you can enter, the screen will also be displayed to you! Therefore, there are two types of outputs: Correct and wrong! (Known as stdout and stderror respectively) for example, the following execution result: "find:/home/root: Permission denied" tells you that you do not have permission to access the data folder, this is the output of the error, so "/home/dmtsai/tseting" is the correct output!

[Dmtsai @ Linux ~] $ Find/home-name Testing
Find:/home/test1: Permission denied <= starndard Error
Find:/home/root: Permission denied <= starndard Error
Find:/home/masda: Permission denied <= starndard Error
/Home/dmtsai/testing <= starndard output

Well, what if we want to output data to the list file? What are the results of executing "find/-name testing> list? Haha, you will find that the "correct" output data is stored in the list, and there will still be an error message on the screen! Headache! What should I do if I want to save the correct and wrong data to different files ?! Haha! In terms of data redirection, the correct method should be "1>" and "2>! However, if there is only>, the default value is 1>! That 1> is the output of the correct data, 2> is the output of the wrong data project. That is to say:

1>: outputs the correct data to the specified place.
2>: outputs the error data to the specified location.

Well, in the above example, how do we output data to different places? This can be written as follows:

[Dmtsai @ Linux ~] $ Find/home-name testing> list_right 2> list_error

In this way, the rows of errors with permission in the execution results will all go to the list_error file. The correct output data will be saved to the list_right file! Can this be understood? If it is a bit confusing, take a rest and try again !! Again, if I only need the correct data, I will not need the wrong information? Well, the/dev/null garbage bin is very important at this time! What is/dev/null? Basically, it is like a "black hole" waste bin function! When anything you enter is directed to this virtual waste bin device, "it will disappear out of thin air ~~』, This is useful! For example, in the above example, we can do this to discard the error message!

[Dmtsai @ Linux ~] $ Find/home-name testing> list_right 2>/dev/null

Amazing! The error message will "disappear !』 Haha! So happy! What if I want to write all the data to the same file? At this time, special writing is required. Please note the following!

[Dmtsai @ Linux ~] $ Find/home-name testing> List 2> List <= incorrect syntax
[Dmtsai @ Linux ~] $ Find/home-name testing> List 2> & 1 <= Correct syntax

Please pay special attention to this! You need to use 2> & 1 to write data to the same file at the same time! OK! After learning about >,2 >>>> and/dev/null, what is <!? Haha! In the simplest statement, it means reading data that needs to be input by the keyboard through the file. For example, we can use Cat to input some data on the keyboard and then write it into a file. For example:

[Root @ Linux ~] # Cat> catfile
Testing
Cat file test
<= Click [CTRL] + D here to end the input!

At this time, a catfile file will be generated, and the file content is just entered. Can I replace keyboard input with other files? Yes! Do this!

[Root @ Linux ~] # Cat> catfile <somefile

I can edit somefile first, and then output the data to the catfile command described above! Can this be understood? After being able to understand <, it would be a nightmare to come back again <this two consecutive symbols smaller ~ It indicates the ending input character! For example, "I want to use Cat to directly output the input message to the catfile, and when the EOF is input, the input ends.", I can do this:

[Root @ Linux ~] # Cat> catfile <EOF
> This is a test testing
> OK now stop
> EOF <= enter this item, hey! It's over now!

Have you seen it? With the <control character on the right side, we can terminate an input without entering [crtl] + D! This is very helpful for programming! Well, why do we need to use command output for redirection? This problem will surely affect your attention, if you have never written a script! Let's talk about it!

  • When the screen output information is very important and we need to save it
  • When the program in the background execution does not want him to interfere with the normal output results of the screen;
  • The execution result of some system routine commands (such as files written in/etc/crontab;
  • When executing some commands, we already know the possible error messages, so we want to discard them with "2>/dev/null;
  • When the error message and the correct message need to be output separately.

Of course, there are still many features. The simplest thing is that netizens often ask: "Why does my root get an error message from the system crontab?" This is a common error.
If we already know that this error message can be ignored, um! "2> errorfile" is very important! Do you understand ??

Command Execution judgment basis:;, &, |

In some cases, we want to execute multiple commands at a time. For example, when I shut down the computer, I want to execute two syncs before shutdown the computer. What can I do? Do this:

[Root @ Linux ~] # Sync; sync; shutdown-H now

Use semicolons (;) in the middle of the instruction to separate the instruction. As a result, after the instruction before the semicolon is executed, the subsequent instruction will be executed immediately. This is really convenient ~ Let's look at it from another perspective. If I want to create an archive under a directory, that is, if the directory exists, I will create this archive. If it does not exist, forget it ~ If the directory exists, you can use some bash-provided declarative functions. But here we assume that I do not know the command, but I know that I can use ls to determine whether the directory exists. That is to say, I can use ls directoryname to determine whether a file exists and use touch to create a file. These two commands are related. How can I write them? Haha! You can use & to do this!

[Root @ Linux ~] # Ls/tmp & Touch/tmp/testingagin

Do you remember we talked about this strange variable in the Variable Section "$? ? If there is no error message in the command execution result, $? will be returned? = 0. If there is an error, the return value will not be 0! Through this judgment, we can also use & to determine that the execution result of the current command is correct (for example, when only standard output is available), we can then execute subsequent commands, otherwise, it will be skipped! Therefore, if ls/tmp is correct, touch/tmp/testingagin will be executed! In case:

[Root @ Linux ~] # Ls/vbird & Touch/vbird/test

This is because the/vbird directory cannot exist in my system! Therefore, if you execute ls/vbird, an error will be returned, so the subsequent touch/vbird/test will naturally not act! Do you understand? From another perspective, if I want to create a file if it does not exist, I will skip this step? Very easy ~ You can do this:

[Root @ Linux ~] # Ls/tmp/vbirding | touch/tmp/vbirding

That | exactly the same as & On the contrary. When an error occurs in the current command, the following command will be executed! (Note that | Yes |, and | the key is the backslash \ The same button. Therefore, the one will appear when you press [shift] and add [\]. | hello !) Therefore, when an error occurs in LS/tmp/vbirding, touch/tmp/vbirding is used to create the file. Is it interesting? This | and & is useful for system administrators when managing certain file permissions and problems! Now, it's a little difficult to play. Let's take a look at the example below:

Example: Use ls to test whether/tmp/vbirding exists. If yes, "exist" is displayed. If no exist exists, "not exist" is displayed "!

This involves the issue of logical judgment. If a data is displayed and other data is displayed if no data exists, I can do this:

Ls/tmp/vbirding & Echo "exist" | echo "not exist"

This means that after ls/tmp/vbirding is executed, if it is correct, Echo "exist" will be executed. If there is a problem, Echo "not exist" will be executed "! If I write:

Ls/tmp/vbirding | echo "not exist" & Echo "exist"

Right? This is actually a problem. Why? Because commands are executed one by one, in the preceding example, if/tmp/vbirding does not exist, it will:

1. If ls/tmp/vbirding does not exist, a non-zero value is returned;
2. next, after | judgment, it is found that the previous command returns a value other than 0. Therefore, the program starts to execute echo "not exist ", the echo "not exist" program can certainly be executed successfully, so a zero value will be returned to the subsequent command;
3. After & judgment, success! It's 0! So we started to execute echo "exist ".

So ah, hey! In the second example, both not exist and exist appear! Amazing ~ After the exercises in this example, you should know that because the commands are executed one by one
So, if you really want to use judgment, the order of & | cannot be wrong ~ Generally,

There can be a maximum of three types, namely:

Command1 & command2 | command3

In addition, the Order will not change, because in general, command2 and command3 will place commands that can certainly be successfully executed. Therefore, based on the logic analysis in the above example, you will know why this is the case.
Placement ~ This is useful!

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.