Bash stderr 重定向在某些情况下不起作用

Bash stderr redirection doesnt work in some cases

我有两个案例要分享,我没有发现 stderr 重定向 (2>) 按预期工作:

在这两种情况下,正在执行操作的 file/directory 都不存在。

案例 1:

当您在管道中给出 2 个命令时:

[root@example ~]# cat test2.txt | grep -i 'third'
cat: test2.txt: No such file or directory

[root@example ~]# cat test2.txt | grep -i 'third' 2> /dev/null
cat: test2.txt: No such file or directory

但是重定向仅与 grep 作为命令一起工作:

[root@example ~]# grep -i 'third' test2.txt 
grep: test2.txt: No such file or directory

[root@example ~]# grep -i 'third' test2.txt 2> /dev/null
<redirection worked properly>

我知道先使用 cat 然后再使用 grep 没有意义,但我只是好奇而已。

案例二:

当您使用 tree 命令时:

[root@example ~]# tree /var/crash2
/var/crash2 [error opening dir]

0 directories, 0 files

[root@example ~]# tree /var/crash2 2> /dev/null
/var/crash2 [error opening dir]

0 directories, 0 files

但是 ls 命令不是这样的:

[root@example ~]# ls -ld /var/crash2
ls: cannot access /var/crash2: No such file or directory

[root@example ~]# ls -ld /var/crash2 2> /dev/null
<redirection worked properly>

哪里出了问题?

  1. cat 有一个错误,不是 Cyrus 提到的 grep

  2. tree 命令在标准输出中显示 "error opening dir"

所以命令显示如果我们使用 2>/dev/null

root@ubuntu:~# tree -if test 2>/dev/null
test [error opening dir]

0 directories, 0 files

你提到的同样的事情之前被报告为一个错误,参考:https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=76594