Bash:检查stdin但是将其完整地转发给另一个程序?

时间:2015-09-01 16:41:37

标签: linux bash stdin

此处有许多示例,使用while read line使用bash接收stdin

但是我只想检查stdin,而不是销毁或修改它,并在退出时完整地转发给另一个程序(期待stdin)。

这可能吗?这是tee解决方案吗?可以在没有tee的情况下完成吗?

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

2 个答案:

答案 0 :(得分:2)

You can use coproc and group command ({}) for this. I came up with the following:

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 by default creates an array named COPROC holding the file descriptors for the stdin/stdout of the command executed by it. But after the first use (read) it would be closed, so you have to copy it (<&) to a dedicated one (200). After the loop, you have the firstline variable set and you can use it to parametrize the second command. Of course if you only care about the first line then don't use a loop. That is just for the sake of the example. The other thing is that if you want to stream into the stdin of the second command then you have to batch the generated output together with a group command. This way you don't have to use tempfiles.

You can find out everything about these in man bash.

答案 1 :(得分:1)

When you must determine how to start secondprog after examining the output, you must wait for the firstprog to be finished. So you can let the examiner start the secondprog, using the input stored in a file.

firstprog | tee outfile | myfilter.sh

with some logic to make an optionlist (make a function like my_inspect)

optionlist=""
while read -r line; do 
   optionlist+=$(my_inspect "${line}")
done
secondprog ${optionlist} < outfile
rm outfile