The use of 2>&1 in input and output redirection in Linux (transfer)

The use of 2>&1 in input and output redirection in Linux (transfer)

 

Example

 

1) command 2>errfile: The error of command is redirected to the file errfile.

2) command 2>&1 | ...: The error of the command is redirected to the standard output, and both the error and the standard output are passed to the next command through the pipeline .

3) var=`command 2>&1`: The error of command is redirected to standard output, and both error and standard output are assigned to var.

4) command 3>&2 2>&1 1>&3 | ...: to achieve the exchange of standard output and error output.

5) var=`command 3>&2 2>&1 1>&3`: realize the exchange of standard output and error output.

6) command 2>&1 1>&2 | ... (wrong...) : This cannot achieve the exchange of standard output and error output. Because the shell executes commands from left to right , after executing 2>&1, the error output is already the same as the standard output, and it is meaningless to execute 1>&2 again.

 

"2>&1 file"和 "> file 2>&1"区别

 

1) cat food 2>&1 >file : Standard output is redirected to file file, and errors are output to the terminal.

2) cat food >file 2>&1 : The error output is redirected to the same as the standard output, the standard output is redirected to the file file, and then both the error and the standard are output to the file file.

 

 

Replenish

       Normally open files are closed automatically when the process exits, but it is better to close them immediately when you are done using them. Use m<&- to close the input file descriptor m and m>&- to close the output file descriptor m. If you need to close standard input use <&-; >&- is used to close standard output.

 

Original address: http://www.cnblogs.com/yangyongzhi/p/3364939.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326801268&siteId=291194637
Recommended