我没有任何名为"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
。