热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

管道是否会阻止它的执行中途?[重复]-Doespipinglstoheadstopit'sexecutionhalfway?[duplicate]

Thisquestionalreadyhasananswerhere:这个问题在这里已有答案:Bash:Head&Tailbehaviorwit

This question already has an answer here:

这个问题在这里已有答案:

  • Bash: Head & Tail behavior with bash script 3 answers
  • Bash:使用bash脚本3答案的头部和尾部行为

If I run ls folder | head in a directory with a lot of files, the execution time is about 50 times faster than ls folder | tail. Does the head command stops ls from executing wholy when it has enough (10) lines?

如果我运行ls文件夹|在一个包含大量文件的目录中,执行时间比ls文件夹快约50倍尾巴。当head命令有足够的(10)行时,head命令会阻止ls执行wholy吗?

I couldn't find the answer to this anywhere because "pipe to head" gives me tons of unrelated results on Google or here.

我无法在任何地方找到答案,因为“管道到头”在谷歌或这里给了我大量无关的结果。

If the answer is no, then is there a more efficient way to list only some files instead of running ls completely and cutting the output with head?

如果答案是否定的,那么是否有更有效的方法来列出一些文件,而不是完全运行ls并用头部切割输出?

2 个解决方案

#1


11  

Once head has read enough lines from it's stdin (stdout of ls), then it exits and therefore closes the stdin. When that happens, the pipe is considered to be broken and ls receives a SIGPIPE signal. As a reaction to that it terminates as well, way before processing everything that it would normally do. In the case of tail, it has to wait for ls to terminate to know which X number of lines were the last ones.

一旦head从它的stdin(stdout of ls)中读取了足够的行,那么它就会退出并因此关闭stdin。当发生这种情况时,管道被认为是损坏的并且ls接收到SIGPIPE信号。作为对它的反应,它也会在处理通常所做的一切之前终止。在tail的情况下,它必须等待ls终止以知道哪些X行是最后一行。

#2


0  

This would be more efficient as no new processes are created:

由于没有创建新进程,因此效率更高:

a=( folder/* )
echo ${a[@]:0:9}

In same cases it may be even better as you don't have to prepend folder/ if you want to do something with the result.

在相同的情况下,它可能会更好,因为您不必在文件夹前添加/如果您想对结果执行某些操作。


推荐阅读
author-avatar
kanney姜_958
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有