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
Best Answer
String matching, optionally including regex matching
grep
is a standard utility which seems to do exactly what you want: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:grep
is a powerful utility with many options. Seeman grep
for details.Examples
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:Mathematical expressions can be used:
Non-numeric ordering can also be tested: