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
up vote 1 down vote accepted

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
$ 
  • grep does exactly that, but is only useful with strings - i'd like to be able to use this with numerical and boolean conditions as well. I'll edit my question to mention that – Slimior Jun 3 '16 at 0:04
  • @Slimior Very good. In that case, try awk. (see updated answer for an example.) – John1024 Jun 3 '16 at 0:08
  • 1
    how could I not think about awk, so simple and elegant - exactly what i was looking for, thanks :) – Slimior Jun 3 '16 at 0:12

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.