简体   繁体   English

`cat |`和`<`之间有什么区别?

[英]What is the difference between `cat |` and `<`

I'd like to send the contents of filename to some_cmd on the command line. 我想在命令行some_cmd filename的内容发送到some_cmd What's the difference between running this: 运行这个有什么区别:

$ cat filename | some_cmd

and

$ some_cmd < filename

Are there cases where I can or should use one and not the other? 有哪些情况我可以或应该使用一个而不是另一个?

  • cat foo | somecmd cat foo | somecmd is running two programs— /bin/cat , and somecmd ; cat foo | somecmd正在运行两个程序 - /bin/catsomecmd ; and connecting the stdout of cat to the stdin of somecmd with a FIFO—which can be read only once, from start to back. 并使用FIFO将cat的stdout连接到somecmd的stdin, somecmd只能读取一次。 That FIFO also doesn't expose metadata about the original file—neither its name nor its size can be discovered by somecmd (without, for size, reading all the way to the end; this makes cat foo | tail ridiculously slow for a multi-GB file). 该FIFO也不会暴露有关原始文件的元数据 - somecmd既不能发现它的名称也不能发现它的大小(没有,对于大小,一直读到最后;这使得cat foo | tail for a ridiculously slow for a multi- GB文件)。

  • somecmd <foo is running only one program— somecmd —connecting its stdin to a direct handle on the file foo . somecmd <foo只运行一个程序 - somecmd - 将其stdin连接到文件foo上的直接句柄。 It can thus copy that handle, rewind and reread it, hand out subsets of the file to different threads to process in parallel, map the file into memory for random access, etc. 因此,它可以复制该句柄,倒回并重新读取它,将文件的子集分发给不同的线程以并行处理,将文件映射到内存中以便随机访问等。

Common programs like GNU sort , wc -c , tail and shuf can run much more efficiently when given a real, seekable file handle rather than a FIFO. GNU sortwc -ctailshuf等常用程序在给定真实的可搜索文件句柄而不是FIFO时可以更有效地运行。

Always use redirection directly from a file rather than cat 'ing that file unless you have a specific and compelling reason to do otherwise. 始终使用重定向直接从一个文件,而不是cat荷兰国际集团这个文件,除非你有一个具体的和令人信服的理由不这样做。”


As an example of such a compelling reason (where you might want to use cat ), consider the case where you need to stream a file only readable by a more-privileged user account. 作为这种令人信服的理由(您可能希望使用cat )的示例,请考虑您需要流式传输仅由更多特权用户帐户读取的文件的情况。

sudo -u someuser /bin/cat -- /path/to/somefile | somecmd

...lets somecmd run with your original, non-escalated privileges, so /etc/sudoers can be configured to allow the original command to run only that single, specific cat invocation. ...让somecmd以原始的非升级权限运行,因此可以配置/etc/sudoers以允许原始命令仅运行该单个特定的cat调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM