What do 1 and 2 stand for in Linux
In Linux system 0 1 2 is a file descriptor
It can be seen from the above table that we usually use
echo "hello" > t.log
In fact, it can also be written as
echo "hello" 1> t.log
About the meaning of 2>&1
I won’t elaborate on input/output redirection in this article. If you don’t understand, please refer to here: Shell: Pipes and Redirection
- Meaning: Redirect standard error output to standard output
The symbol >& is a whole and cannot be separated. After being separated, it will not have the above meaning.
- For example, some people might think like this: 2 is standard error input, 1 is standard output, and> is a redirection symbol. Then, should "redirect standard error output to standard output" be written as "2>1"? Is that right?
- If you have tried it, you will know that the wording of 2>1 actually redirects the standard error output to a file named "1".
- It’s not possible to write 2&>1
Why 2>&1 should be put at the back
Consider the following shell command
nohup java -jar app.jar >log 2>&1 &
(The last & means put the command in the background for execution, it is not the focus of this article, you can Google it yourself if you don’t understand it)
Why 2>&1 must be written after >log, which means that both standard error output and standard output are directed to log?
We might as well understand 1 and 2 as a pointer, and then look at the above statement is like this:
本来1----->屏幕 (1指向屏幕)
执行>log后, 1----->log (1指向log)
执行2>&1后, 2----->1 (2指向1,而1指向log,因此2也指向了log)
``
再来分析下
nohup java -jar app.jar 2>&1 >log &
本来1----->屏幕 (1指向屏幕)
执行2>&1后, 2----->1 (2指向1,而1指向屏幕,因此2也指向了屏幕)
执行>log后, 1----->log (1指向log,2还是指向屏幕)
So this is not the result we want.
Simply do a test to test the above ideas:
The java code is as follows:
public class Htest {
public static void main(String[] args) {
System.out.println("out1");
System.err.println("error1");
}
}
After javac is compiled, run the following command:
java Htest 2>&1 > log
You will see only "error1" is output on the terminal, and only "out1" in the log file
It is too troublesome to write ">log 2>&1" every time, can you abbreviate it?
There are two abbreviations
&>log
>&log
For example, the wording in the above section can be abbreviated as:
nohup java -jar app.jar &>log &
The above two methods have the same semantics as ">log 2>&1".
So is there a difference between &> and >& in the above two methods?
There is no difference in semantics, but the first method is the best choice, and the first method is generally used.
Author: A Walking People
Original: https://blog.csdn.net/zhaominpro/article/details/82630528
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。