Shell重定向i/o命令 [英] Shell redirection i/o order
问题描述
我在玩 i/o shell 重定向.我尝试过的命令(在 bash 中):
ls -al *.xyz 2>&1 1>文件.lst
和
ls -al *.xyz 1>文件.lst 2>&1
当前文件夹中没有任何*.xyz
文件.
这些命令给了我不同的结果.第一个命令在屏幕上显示错误消息 ls: *.xyz: No such file or directory
.但是第二个会将此错误消息打印到文件中.为什么第一个命令没有将错误输出写入文件?
这个错误:
ls: *.xyz: 没有那个文件或目录
正在由 ls
二进制写入 stderr
.
但是在这个命令中:
ls -al *.xyz 2>&1 1>文件.lst
您首先将 stderr
重定向到 stdout
,默认情况下会转到 tty
(终端)>
然后您将 stdout
重定向到文件 files.lst
,但是请记住 stderr 不会重定向到文件,因为您有 stderr
到 stdout
重定向 before stdout
到 file
重定向.在这种情况下,您的 stderr
仍会写入 tty
.
但是,在第二种情况下,您更改重定向的顺序(首先 stdout
到 file
,然后 stderr
到 stdout
>) 并且正确地将 stderr
重定向到一个 file
也被 stdout
使用.
I'm playing with i/o shell redirection. The commands I've tried (in bash):
ls -al *.xyz 2>&1 1> files.lst
and
ls -al *.xyz 1> files.lst 2>&1
There is no any *.xyz
file in current folder.
These commands gives me the different results. The first command shows an error message ls: *.xyz: No such file or directory
on the screen. But the second one prints this error message to the file. Why did the first command failed to write an err output to the file?
This error:
ls: *.xyz: No such file or directory
is being written on stderr
by ls
binary.
However in this command:
ls -al *.xyz 2>&1 1> files.lst
You're first redirecting stderr
to stdout
which by default goes to tty
(terminal)
And then you're redirecting stdout
to a file files.lst
, however remember that stderr doesn't redirected to file since you have stderr
to stdout
redirection before stdout
to file
redirection. Your stderr
still gets written to tty
in this case.
However in 2nd case you change the order of redirections (first stdout
to file
and then stderr
to stdout
) and that rightly redirects stderr
to a file
which is also being used by stdout
.
这篇关于Shell重定向i/o命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!