2>&1 正在给出两个 ouptut

  • 本文关键字:两个 ouptut linux bash
  • 更新时间 :
  • 英文 :


我没有任何名为"new"因此它被重定向到test.txt(stedrr)

cat new 2> test.txt

但是为什么我得到2 stderr输出当我运行下面的命令?

cat new 2>&1 test.txt
cat: new: No such file or directory
cat: new: No such file or directory

结果如下:

$ cat new 2>&1 test.txt
cat: new: No such file or directory
cat: test.txt: No such file or directory

注意,它报错了两个不同的文件。

解释。

cat命令的语法为:

cat [OPTION]... [FILE]...

换句话说,它(可能)获取多个文件并将它们写入标准输出。在上面的例子中,命令打印No such file or directory两次,因为您给了它2个不同的输入不存在的文件。

等待?怎么啦?2个输入文件?

Yes ! !

命令中,2>&1表示将标准错误发送到与标准输出相同的位置。但是由于您没有重定向标准输出…它进入控制台。

如果你想让标准错误和标准输出都到一个文件中,你也需要重定向标准输出;例如

$ cat > new 2>&1 test.txt
$ cat new
cat: test.txt: No such file or directory

现在new将包含cat写入标准错误的错误消息!

相反,如果您想要test.txt中的输出和错误,则为:

$ cat > test.txt 2>&1 new
$ cat test.txt
cat: new: No such file or directory

…或者new的内容…


你为什么得到这个?

$ cat new 2>&1 test.txt
cat: new: No such file or directory
cat: new: No such file or directory

嗯,我的猜测test.txt实际上存在…它包含

cat: new: No such file or directory

从上次尝试:

$ cat new 2> test.txt

将(仅!!)错误写入test.txt

最新更新