In-depth understanding of the meaning of 2>&1 in Linux shell (the most comprehensive on the entire network, you will understand after reading it)

Release: 2023-08-03 16:14:33
forward
1344 people have browsed it

What do 1 and 2 represent in Linux?

In Linux system 0 1 2 is a file descriptor

In-depth understanding of the meaning of 2>&1 in Linux shell (the most comprehensive on the entire network, you will understand after reading it)
##As can be seen from the above table, the

echo "hello" > t.log
Copy after login

we usually use can actually be written as

echo "hello" 1> t.log
Copy after login

About 2> The meaning of &1

I won’t go into details about input/output redirection in this article

  • 含义:将标准错误输出重定向到标准输出
  • 符号>&是一个整体,不可分开,分开后就不是上述含义了。
    • 比如有些人可能会这么想:2是标准错误输入,1是标准输出,>是重定向符号,那么"将标准错误输出重定向到标准输出"是不是就应该写成"2>1"就行了?是这样吗?
    • 如果是尝试过,你就知道2>1的写法其实是将标准错误输出重定向到名为"1"的文件里去了
  • 写成2&>1也是不可以的

为什么2>&1要放在后面

考虑如下一条shell命令

nohup java -jar app.jar >log 2>&1 &
Copy after login

(最后一个&表示把条命令放到后台执行,不是本文重点,不懂的可以自行Google)

为什么2>&1一定要写到>log后面,才表示标准错误输出和标准输出都定向到log中?

我们不妨把1和2都理解是一个指针,然后来看上面的语句就是这样的:

本来1----->屏幕 (1指向屏幕)
执行>log后, 1----->log (1指向log)
执行2>&1后, 2----->1 (2指向1,而1指向log,因此2也指向了log)
``
再来分析下
Copy after login

nohup java -jar app.jar 2>&1 >log &

本来1----->屏幕 (1指向屏幕)
执行2>&1后, 2----->1 (2指向1,而1指向屏幕,因此2也指向了屏幕)
执行>log后, 1----->log (1指向log,2还是指向屏幕)
Copy after login

所以这就不是我们想要的结果。

搜索公众号GitHub猿后台回复“打飞机”,获取一份惊喜礼包。

简单做个试验测试下上面的想法:

java代码如下:

public class Htest {
    public static void main(String[] args) {
        System.out.println("out1");
        System.err.println("error1");
    }
}
Copy after login

javac编译后运行下面指令:

java Htest 2>&1 > log
Copy after login

你会在终端上看到只输出了"error1",log文件中则只有"out1"

每次都写">log 2>&1"太麻烦,能简写吗?

有以下两种简写方式

&>log
>&log
Copy after login

比如上面小节中的写法就可以简写为:

nohup java -jar app.jar &>log &
Copy after login

上面两种方式都和">log 2>&1"一个语义。

那么 上面两种方式中&>和>&有区别吗?

语义上是没有任何区别的,但是第一中方式是最佳选择,一般使用第一种。

The above is the detailed content of In-depth understanding of the meaning of 2>&1 in Linux shell (the most comprehensive on the entire network, you will understand after reading it). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Linux中文社区
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template