How might a node in a Bash pipeline only peek at, but not consume, its input stream?
For example, how might I modify the following script so that it outputs "print" instead of nothing? In particular, how might I modify or replace grep --quiet print
so that it only peeks at, but does not consume, its input?
printf "%s\n" a b print c |
if grep --quiet print
then
grep print | cat
fi
Output:
Desired output:
print
Ideally, I seek a program peek
that is similar to grep
, but that doesn't consume its input. peek print
would return error code 0 if it finds "print" in the input and if not, returns a non-zero error code.
Here's how peek
would work in my example:
printf "%s\n" a b print c |
if peek print
then
grep print | cat
fi
Output:
print
The reason I want to do this instead of simply filtering the results with grep print
is to avoid processing empty search results that might cause an error.
cvsq
) only if its input (eg. the result ofgrep
) is not empty, then you probably don't have to save the entire search result in a variable or tempfile, a single byte should suffice:PRODUCER | grep PATTERN | { t=$(dd bs=1 count=1 2>/dev/null; printf x); t=${t%x}; [ "$t" ] && { printf '%s' "$t"; cat; } | CONSUMER; }
tee(2)
system call, but there's no generally available shell utility that can use it, so the only thing left are such hacks.