Chapter 2 understanding and learning bash data stream redirection

Source: Internet
Author: User

Data Stream redirection refers to the data that should appear on the screen after a command is run, directing it to other places, such as files or devices (such as printers )!

What is data stream redirection?

The command runs as follows:


Figure 5.1.1 data transmission during command running

When running a command, the command may read data from the file and output the data to the screen after processing. Standard output and standard error output represent "standard output" and "standard error output" respectively. They are all output to the screen by default!

 

  • Standard output and standard error output

Standard output refers to the "correct information returned by the Command run", and the standard error output can be understood as the "error message returned after the command fails to run 』. For example, our system has/etc/crontab by default, but no/etc/vbirdsay, at this time, if you issue the "cat/etc/crontab/etc/vbirdsay" command, cat will:

  • Standard output: Read/etc/crontab and display the file content on the screen;
  • Standard Error output: the error message is displayed on the screen Because/etc/vbirdsay cannot be found.

No matter whether the correct or wrong data is output to the screen by default, the information displayed on the screen will be messy! Can we separate these two data sets through some mechanisms? Of course! That is the function of data stream redirection! Data Stream redirection can transfer standard output (stdout) and standard error output (stderr) to other files or devices respectively, and the special characters used for transmission are 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>;

 

Example 1: Observe the file names, permissions, and attributes of the directories under your system root directory (/), and record them [email protected] ~] # Ll/<= the file name is displayed on the screen [[email protected] ~] # Ll/> ~ /Rootfile <= no information on the screen [[email protected] ~] # LL ~ /Rootfile <= a new file has been created! -RW-r -- 1 Root 1089 Feb 6 17: 00/root/rootfile

The data originally displayed in "ll/" has been redirected ~ /Rootfile is in the file! That ~ /The file name of rootfile can be retrieved at will. If you issue "cat ~ /Rootfile, you can see the data on the screen. If I try again: "ll/Home> ~ /Rootfile, ~ /What is the content of the rootfile? It will become "only LL/home data! The original "ll/" data is gone! Because the file is created in the following way:

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

If you want to accumulate data without deleting the old data, use two symbols (>) that are greater than the old one )! For the above example, you should change it to "ll/> ~ /Rootfile. In this way, when (1 )~ /When the rootfile does not exist, the system will create the file. (2) If the file already exists, the data will be accumulated at the bottom of the file!

The above is the correct data of standard output. What if it is the error data of standard error output? Then go through 2> and 2>! It is also the feature of overwrite (2>) and accumulate (2>! We just mentioned that the stdout code is 1 and the stderr code is 2, so this 2> is easy to understand. If only> exists, it indicates the Default Code 1! That is to say:

  • 1>: output "correct data" to the specified file or device in a overwriting method;
  • 1>: outputs "correct data" to a specified file or device in a cumulative manner;
  • 2>: overwrite the "wrong data" to the specified file or device;
  • 2>: outputs "wrong data" to the specified file or device in an accumulative way;

Note that there are no spaces in between "1>" and "2>! When you run the find command as a normal identity, some errors may occur due to permission issues. For example, when you run "find/-name testing", information such as "find:/root: Permission denied" may be generated. For example, the following example:

Example 2: search for a file named. bashrc under/home using a general identity account. [email protected] ~] # Su-dmtsai <= assume that my system is named dmtsai account [[email protected] ~] $ Find/home-name. bashrc <= The ID is dmtsai! Find:/home/lost + found: Permission denied <= standard errorfind:/home/ALEX: Permission denied <= standard errorfind:/home/arod: permission denied <= standard error/home/dmtsai /. bashrc <= standard output

Run "find/home-name. bashrc> List". The "correct" output data is saved in the list. An error message is displayed on the screen!

Example 3: Example 2: store stdout and stderr in different files [email protected] ~] $ Find/home-name. bashrc> list_right 2> list_error

At this time, "No information will appear on the screen 』!

  • /Dev/null waste bin black hole device and special Writing Method

 

Example 4: Example 3: discard the wrong data and display the correct data on the screen [[email protected] ~] $ Find/home-name. bashrc 2>/dev/null/home/dmtsai/. bashrc <= only stdout is displayed on the screen, and stderr is discarded.

Write correct and wrong data to the same file:

Example 5: write all the command data to the file named list [[email protected] ~] $ Find/home-name. bashrc> List 2> List <= Error [email protected] ~] $ Find/home-name. bashrc> List 2> & 1 <= correct [email protected] ~] $ Find/home-name. bashrc &> List <= Correct

The first row of the above table is incorrect because the two pieces of data are written to a file at the same time, and no special syntax is used. At this time, the two pieces of data may be written into the file at the same time, this leads to disordered order. Therefore, although the final list file will still be generated, the data arrangement in it will be strange, rather than the output sorting on the original screen. The special syntax for writing data to the same file is shown in the table above. You can use 2> & 1 or! Generally, laruence is used to the syntax of 2> & 1!

  • Standard Input: <and <

"Replace the data originally required by the keyboard with the file content 』

Example 6: Use the cat command to create a file. [[email protected] ~] # Cat> catfiletestingcat file test <= click [CTRL] + D to exit [email protected] ~] # Cat catfiletestingcat file test

The catfile will be automatically created after the entry> CAT, and the content is the two rows of data just entered on the keyboard. :

Example 7: Use stdin to replace keyboard input to create a new file [[email protected] ~] # Cat> catfile <~ /. Bashrc [[email protected] ~] # Ll catfile ~ /. Bashrc-RW-r -- 1 Root 194 Sep 26 13:36/root /. bashrc-RW-r -- 1 Root 194 Feb 6 catfile # note that the sizes of the two files will be the same! It is almost like copying with CP!
[[Email protected] ~] # Cat> catfile <"EOF"> This is a test.> OK now stop> EOF <= enter this keyword. It will end immediately without entering [CTRL] + d [[email protected] ~]. # Cat catfilethis is a test. OK now stop <= only the two rows exist. There is no line for the keyword!

 

  • The screen output information is very important, and we need to save it;
  • When a program running in the background does not want him to interfere with the normal output of the screen;
  • The running result of some system routine commands (such as files written in/etc/crontab;
  • If you want to discard the error message "2>/dev/null" when running commands that may be known;
  • When the error information and the correct information need to be output separately.

 

Command running judgment basis:;, &, |



  • CMD; cmd (continuous command issuing without considering command relevance)

:

[[email protected] ~]# sync; sync; shutdown -h now



  • $? (Command return value) and

There is dependency between the two commands, and the dependency mainly determines whether the result of the previous command is correct.

Command issuing status Description
Cmd1 & cmd2 1. If cmd1 is completed and runs properly ($? = 0) to start running cmd2.
2. If cmd1 is finished and is incorrect ($? 0), then cmd2 does not run.
Cmd1 | cmd2 1. If cmd1 is completed and runs properly ($? = 0), then cmd2 does not run.
2. If cmd1 is finished and is incorrect ($? 0) to start running cmd2.

 

Example 1: Use ls to check whether/tmp/ABC exists. If yes, use touch to create/tmp/ABC/hehe [[email protected] ~]. # Ls/tmp/ABC & Touch/tmp/ABC/hehels:/tmp/ABC: no such file or directory # This directory cannot be found in LS simple instructions, but there is no touch error, indicating that touch is not running [[email protected] ~] # Mkdir/tmp/ABC [[email protected] ~] # Ls/tmp/ABC & Touch/tmp/ABC/hehe [[email protected] ~] # Ll/tmp/ABC-RW-r -- 1 Root 0 Feb 7 12:43 hehe

 

Example 2: Test whether/tmp/ABC exists. If it does not exist, create it. If it exists, do nothing [email protected] ~] # Rm-r/tmp/ABC <= Delete this directory first to facilitate the test [[email protected] ~] # Ls/tmp/ABC | mkdir/tmp/abcls:/tmp/ABC: no such file or directory <= really does not exist! [[Email protected] ~] # Ll/tmp/ABC total 0 <== the result is displayed! With mkdir

 

Example 3: I do not know whether/tmp/ABC exists, but I want to create the/tmp/ABC/hehe file [[email protected] ~] # Ls/tmp/ABC | mkdir/tmp/ABC & Touch/tmp/ABC/hehe

Since the commands in Linux run from left to right, we can analyze the following results in Example 3:

  • (1) If/tmp/ABC does not exist, return $? 0, then (2) Because | $? Therefore, mkdir/tmp/ABC is started. Because mkdir/tmp/ABC is successful, return $? = 0 (3) because & encounters $? If it is set to 0, touch/tmp/ABC/hehe is run, And hehe is created;

  • (1) If/tmp/ABC exists, return $? = 0, then (2) Because | encounters 0 $? No. $? = 0 continue to pass back, so (3) as & encounters $? = 0. Create/tmp/ABC/Hehe! Finally,/tmp/ABC/hehe is created.

The entire process is illustrated as follows:


Figure 5.2.1 relationship between commands in sequence

 

Example: Use ls to test whether/tmp/vbirding exists. If yes, "exist" is displayed. If no exist exists, "not exist" is displayed "! A: 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 run, if it is correct, Echo "exist" is run. If there is a problem, Echo "not exist" is run "! What will happen if I write it as follows?
Ls/tmp/vbirding | echo "not exist" & Echo "exist"
This is actually a problem. Why? As described in Figure 5.2.1, the command is run one by one. Therefore, in the preceding example, if/tmp/vbirding does not exist, it performs the following actions:
  1. If ls/tmp/vbirding does not exist, a non-zero value is returned;
  2. After |, the previous command returns a non-zero value. Therefore, the program starts to run echo "not exist ", the echo "not exist" program can certainly run successfully, so it will return a value of 0 to the subsequent command;
  3. After & judgment, success! It's 0! Run echo "exist ".
So ah, hey! In the second example, both not exist and exist appear! Amazing ~

 

Command1 & command2 | command3

In addition, the Order will not change, because in general, command2 and command3 will place commands that can certainly run successfully.

 

 

Chapter 2 understanding and learning bash data stream redirection

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.