[Shell] Output redirection 2>&1

Standard output (stdout) and standard error (stderr), the number of Stdout is 1, and the number of stderr is 2.

By default, redirection operators (such as >, | and <) are only applicable to stdout number 1, (service --status-all |& grep network, |& delivers stdout and stderr together to the right standard input ( stdin) process on the stream)

Operator> redirection, direct the output of stderr (number 2) to Stdout (number 1), use descriptor to redirect to other streams, you need to add & in front of it (please note that there can be no spaces between the characters): 2>&1

service --status-all 2>&1 | grep network
 

 

Transfer from: https://blog.csdn.net/rockstar541/article/details/79239029

On the shell:
0 means standard input
1 means standard output
2 means standard error output
> The default is standard output redirection,
which is the same as 1> 2>&1 means to redirect standard error output to standard output.
&>file means to standard output Both output and standard error output are redirected to the file file

 

Speak with examples:


1. grep da * 1>&2 
2. rm -f $(find / -name core) &> /dev/null In the
above two examples, how to understand, & is not put in the background for execution?

Cow solution:

1.& >file or n>&m is an independent redirection symbol, do not understand it separately.

2. Clarify the difference between files and file descriptors.

3.&>file means to redirect standard output and errors to a file.
For example:
rm -f $(find / -name core) &> /dev/null, /dev/null is a file, this file is special, and all are passed to Throw away everything.

4.n>&m means to make file descriptor n a copy of output file descriptor m. The advantage of this is that sometimes when you search for files, it is easy to produce useless information, such as: 2> /dev/null does not display standard error output; in addition, when you run certain commands, error messages It may be very important, so that you can check what is wrong, such as: 2>&1
For example:
Note that in order to facilitate understanding, you must set up an environment so that the grep da * command will have normal output and error output, and then use the following commands respectively Three files are generated:
grep da *> greplog1
grep da *> greplog2 1>&2   
grep da *> greplog3 2>&1 //grep da * 2> greplog4 1>&

#Check greplog3 and you will find that there are both normal output content and wrong output content

Guess you like

Origin blog.csdn.net/bandaoyu/article/details/114295070