管道和文件重定向的区别-BASH [英] Difference in pipe and file redirection - BASH
问题描述
重定向用于重定向stdout/stdin/stderr!例如: ls>log.txt.
管道用于将命令的输出作为另一个命令的输入.例如: ls |grep file.txt
为什么这两个操作员确实在做同一件事?
为什么不只写 ls>grep
传递输出,这不只是一种重定向吗?
我意识到Linux是做一件事,做得好",因此我必须缺少更多的逻辑原因.
您要做需要区别对待的语法功能-并使用>
与 |
就可以了.
如果您在两种情况下都使用过>
,您怎么知道是否
ls>grep
试图写入名为 grep
的文件还是将输入发送到 grep
命令?>
grep
也许不是最好的例子,因为您可能会因为存在 grep
的强制性参数而产生歧义.但是,确实存在(可选)无参数的命令,例如 column
.
其他人在评论中提供了另一个示例: test
可能是指测试输出文件或标准 test
命令 .
另一种查看方式:
您的建议实质上是将>
用作通用的send-output-somewhere运算符,而不考虑目标的类型(文件还是命令).
但是,只有转移了消除歧义的必要,然后在指定 target 时必须消除歧义-它是要输出到的文件还是要运行的命令?
考虑到简单命令的 first 令牌- foo [...] ,该外壳还具有隐式消歧功能.code>只会调用 command -在 operator -
>
级别进行区分以输出到文件 | 用于发送命令的code>是明智的选择.
Redirection is used to redirect stdout/stdin/stderr!
Ex: ls > log.txt.
Pipes are used to give the output of a command as input to another command.
Ex: ls | grep file.txt
Why exactly are these two operators doing the same thing?
Why not just write ls > grep
to pass the output through, isn't this just a kind of redirection also?
I realize Linux is "Do one thing and do it well", so there has to be more of a logical reason that I'm missing.
You do need a differentiating syntax feature - and using >
vs. |
will do just fine.
If you used >
in both scenarios, how would you know whether
ls > grep
is trying to write to a file named grep
or send input to the grep
command?
grep
is perhaps not the best example, as you may then be tempted to disambiguate by the presence of grep
's mandatory arguments; however, (optionally) argument-less commands do exist, such as column
.
that other guy offers another example in the comments: test
may refer to a test output file or to the argument-less invocation of the standard test
command.
Another way of looking at it:
Your suggestion is essentially to use >
as a generic send-output-somewhere operator, irrespective of the type of target (file vs. command).
However, that only shifts the need for disambiguation, and then you have to disambiguate when specifying the target - is it a file to output to or a command to run?
Given that the shell also has an implicit disambiguation feature when it comes to the first token of a simple command - foo [...]
only ever invokes a command - differentiating at the level of the operator - >
for outputting to files, |
for sending to commands - is the sensible choice.
这篇关于管道和文件重定向的区别-BASH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!