conditional pipe in bash
Is there any built-in way in bash to pipe output further if certain test
condition is met?
Essentially I want to know if I have to write following function myself or is there some good-practice-already-done way:
check() {
read temp_var
test "$temp_var" $@ && echo $temp_var
}
which would be used as follows:
$ echo foo | check == "foo" | cat
=> foo
EDIT:
The function above works with all conditions test
can comprehend, including numerical ones, such as
$ echo 42 | check -gt 30 | cat
=> 42
String matching, optionally including regex matching
grep
is a standard utility which seems to do exactly what you want:
echo foo | grep -x 'foo' | cat
I presume that cat
is meant here as a stand-in for a more complex pipeline. If it weren't, then the above, of course, simplifies to:
echo foo | grep -x 'foo'
grep
is a powerful utility with many options. See man grep
for details.
Examples
$ echo 'foo' | grep -x 'foo' | cat
foo
$ echo 'goo' | grep -x 'foo' | cat
$
More complex tests, including numerical tests
grep
is good for strings. For more complex testing, including comparison, inequality, and numerical tests, awk
is very useful. For example:
$ echo 64 | awk '$1 <= 65' | cat
64
$ echo 66 | awk '$1 <= 65' | cat
$
Mathematical expressions can be used:
$ echo 8 | awk '2*$1+1 <= 17' | cat
8
$ echo 9 | awk '2*$1+1 <= 17' | cat
$
Non-numeric ordering can also be tested:
$ echo a | awk '$1 < "b"' | cat
a
$ echo c | awk '$1 < "b"' | cat
$