linux - Bash:检查 stdin 但将其原封不动地转发给另一个程序?

标签 linux bash stdin

<分区>

这里有很多关于 bash 使用 while read line 接收 stdin 的例子

但是我只想检查 stdin,而不是破坏或修改它,然后在退出时将它原封不动地完全转发给另一个程序(期望 stdin)。

这可能吗?这是一个 tee 解决方案吗?没有 tee 可以完成吗?

请注意,在这种情况下,stdin 可能相当大和/或包含二进制文件,所以我不想将它读入字符串,我只需要检查它的开头。

最佳答案

您可以使用 coprocgroup command ( {} ) 为此。我想出了以下内容:

coproc cat .profile  # our "firstprog"
exec 200<&${COPROC[0]}  # to keep it open after the first read

while read -r line; do
  firstline="$line"
  break
done <&200  # feed the loop from our new filedescriptor

{  # open group command to batch the output of the embedded commands
  echo FIRST LINE WAS: $firstline  # reprint the read line(s)
  cat <&200  # copy the rest...
} | sed 's:^:_ :g'  # our "secondprog" just to see things modified

coproc默认创建一个名为 COPROC 的数组保存由它执行的命令的标准输入/标准输出的文件描述符。但是在第一次使用后(read)它会被关闭,所以你必须将它(<&)复制到一个专用的(200)。循环后,你有 firstline变量集,您可以使用它来参数化第二个命令。当然,如果您只关心第一行,则不要使用循环。这只是为了举例。 另一件事是,如果你想流入第二个命令的标准输入,那么你必须将生成的输出与组命令一起批处理。这样您就不必使用临时文件。

您可以在 man bash 中找到有关这些的所有信息.

关于linux - Bash:检查 stdin 但将其原封不动地转发给另一个程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32336861/

相关文章:

linux - 使用 Linux IMA 重新测量文件

python - hcitool lescan不会实时打印到一个文件

bash - 只有 mkdir 如果它不存在

c++ - LD_PRELOAD 导致 linux 命令的段错误

bash - 如何在 bash 中快速滚动到命令历史记录的最新/结尾?

linux - 使用 shell 计算学生的平均分

c - 如何安全地排出标准输入?

php - 从 STDIN 逐行读取

c++ - C 中的 cin.ignore() 等价于什么?

c++ - 为 Python 扩展设置 C/C++ 编译器