【问题标题】:How do I capture the output of a command to a file descriptor in Bourne shell?如何将命令的输出捕获到 Bourne shell 中的文件描述符?
【发布时间】:2009-03-08 23:13:29
【问题描述】:

在 Bourne shell 中捕获命令输出的标准方法是使用 $() 语法:

output=$(mycommand)

但是,对于具有大量输出的命令,这需要 shell 将整个内容作为一个长字符串分配内存。我更愿意找到与 Unix C 函数 popen 道德等价的东西,以获取我可以从 read 获取的新文件描述符:

newfd=popen(mycommand)
while read -u $newfd LINE; do
  #process output
done

这可能吗?

【问题讨论】:

  • bash4 有一个不错的新特性:coproc。这将是您的理想选择!太糟糕了,它还是那么新

标签: shell pipe sh


【解决方案1】:
#!bash
ls | while read X
do 
    echo  $X is a directory entry
done

用您选择的命令替换“ls”

【讨论】:

  • 一看就明白。感谢您的快速回复!
  • 请注意 while 循环在子 shell 中运行,因此它对变量所做的任何更改都不会传递回脚本的其余部分
  • 例如,将ls 替换为find,将echo 替换为printf
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 2021-04-10
  • 2016-05-01
相关资源
最近更新 更多