What is the use of 2>&1 in shell scripting
This question already has an answer here:
The short answer is you are redirecting stderr to stdout so you get both error messages written to FD2 as well as normal output on FD1 written to FD1 . (FD = File Descriptor). It generally allows you to capture the output of error messages you want to save in a log file, etc.. that would otherwise not be captured simply by redirecting stdout to the log.
By way of brief background, your shell has 3 well known file descriptors that cover basic reading and writing:
0 - stdin (your input buffer)
1 - stdout (your normal output descriptor)
2 - stderr (your normal error descriptor)
When you read or write, just about any programming language, including your shell, makes use of these common file descriptors to manage the input/output. In your shell, you have the ability to redirect or combine output from stdout and stderr . The general format is:
m > &n ## where n & m are 1, 2
You can combine, for instance, both the stdout and stderr from any command to a file with:
./someprogram > myfile 2>&1
Which basically says, "take the output from someprogram on stdout redirect it to myfile while including stderr in stdout .
There are several good references, one being BASH Programming - Introduction HOW-TO: All about redirection
Note: Be sure you also understand that redirection can happen on a temporary (per command basis) or can be set for the scope of the script using exec .
上一篇: 什么是&&意味着什么?
下一篇: 在shell脚本中使用2>&1有什么用处
