[英]bash: evaluating stdin while outputting to stdout unaltered
In bash, I want to be able to analyze stdin more or less 'out of band', while copying to stdout without moving it through tmp files, variables, or explicitly named fifos. 在bash中,我希望能够或多或少地“分析”stdin,同时复制到stdout而不通过tmp文件,变量或显式命名为fifos。
Two similar examples: 两个类似的例子:
while read foo; do somefunc $foo; echo "$foo"; done
tee >(grep -qs bar && do_something_but_i_am_trapped_in_a_process_substitution_shell)
line-by-line wouldn't be the end of the world, but I'd prefer something cleaner. 逐行不会是世界末日,但我更喜欢更清洁的东西。
What I'd like to be able to do is something with: exec, file descriptor redirections, and tee, such that I can do something like: 我希望能够做的是:exec,文件描述符重定向和tee,这样我可以做类似的事情:
hasABar=$(grep -qs bar <file descriptor magic> && echo yes || echo no)
... then do something based on whether I have a 'bar', but in the end, stdout is still a copy of stdin. ...然后根据我是否有'bar'做一些事情,但最后,stdout仍然是stdin的副本。
UPDATE: from Kugelman's answer below, I adapted to the following, which both work. 更新:根据Kugelman在下面的回答,我适应了以下内容,两者都有效。
(
exec 3>&1
myVar=$(tee /dev/fd/3 | grep -qs bar && echo yes || echo no)
#myVar=$(grep -qs bar <(tee /dev/fd/3) && echo yes || echo no)
echo "$myVar" > /tmp/out1
)
You could dup stdout to fd 3 and then use tee
to write to both stdout and fd 3 simultaneously. 您可以将stdout复制到fd 3,然后使用
tee
同时写入stdout和fd 3。
exec 3>&1
tee /dev/fd/3 | grep -qs bar
Here's an example of that in action. 这是一个实际的例子。 I bolded the lines I typed.
我加粗了我输入的线条。
$
cat test
#!/bin/bash
exec 3>&1
tee /dev/fd/3 | grep bar >&2
$
./test | wc
foo
bar
bar
foo
^D
3 3 12
See how both grep bar
and wc
processed my input? 看看
grep bar
和wc
如何处理我的输入? grep
found the string "bar" when I typed it, and wc
counted everything I typed. 当我键入它时,
grep
找到了字符串“bar”,并且wc
计算了我键入的所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.