The difference between shell redirection &>file, 2>&1, 1>&2

Source: Internet
Author: User

On the shell:
0 indicates standard input
1 indicates standard output
2 indicates standard error output
> default to standard output redirect, same as 1>
2>&1 means redirecting the standard error output to the standard output.
&>file means to redirect both the standard output and the standard error output to file

To speak with an example:


1. grep da * 1>&2
2. Rm-f $ (Find/-name core) &>/dev/null
The above two examples of & how to understand,& is not put in the background to execute it?

Cow's solution:

1.&>file or N>&m are an independent redirect symbol, do not separate to understand.

2. Clarify the differences between file and file descriptors.

3.&>file indicates redirection of standard output and error to file
For example:
Rm-f $ (Find/-name Core) &>/dev/null,/dev/null is a file, this file is special, and all the things passed to it are discarded.

4.n>&m indicates that the file descriptor n becomes a copy of the output file descriptor m. The advantage of this is that sometimes when you look for files, it is easy to generate useless information, such as: 2>/dev/null function is not to display the standard error output, and when you run certain commands, error messages may be important, so that you can check what is wrong, such as:2>& 1
For example:
Note that for ease of understanding, an environment must be set up so that the Execute grep da* command will have normal output and error output, and then generate three files using the following command, respectively:
grep da * > Greplog1
grep da * > Greplog21>&2
grep da * > greplog32>&1//grep da * 2>greplog4 1>&2 results
#查看greplog1会发现里面只有正常输出内容
#查看greplog2会发现里面什么都没有

#查看greplog3会发现里面既有正常输出内容又有错误输出内容

The difference between shell redirection &>file, 2>&1, 1>&2

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.