Grep shows all lines, not just matches; sets exit status

I pass the output of the egrep command, which I use to make sure that the specific fault line is not displayed.

The team itself, unfortunately, will not return the correct zero exit status on error, so I do it.

command | egrep -i -v "badpattern" 

This works the same as giving me the exit code I want (1 if badpattern is displayed in the output, 0 otherwise), BUT, it will only output lines that do not match the pattern (since the -v switch was intended to be executed ) For my needs, these lines are the most interesting.

Is there a way for grep to just blindly go through all the lines it receives as input, and just give me the exit code as needed?

If not, I thought I could just use perl -ne "print; exit 1 if / badpattern /". I use -n rather than -p because -p does not print a violation line (since it prints after running a single line). So, I use -n and call print myself, which at least gives me the first offensive line, but then the output (and execution) stops there, so I will need to do something like

perl -e '$code = 0; while (<>) { print; $code = 1 if /badpattern/; } exit $code'

which does the whole deal, but not much, is there a simple command line switch for grep that will just do what I'm looking for?

+6
source share
3 answers

Actually, your perl idea is not bad. Try:

 perl -pe 'END { exit $status } $status=1 if /badpattern/;' 

I am sure this is at least as fast as the other options.

+4
source
 $ tee /dev/tty < ~/.bashrc | grep -q spam && echo spam || echo no spam 
+2
source

How do I redirect to / dev / null, from here delete all the lines, but you still get the exit code?

 $ grep spam .bashrc > /dev/null $ echo $? 1 $ grep alias .bashrc > /dev/null $ echo $? 0 

Or you can just use the -q switch

  -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. (-q is specified by POSIX.) 
+1
source

Source: https://habr.com/ru/post/889153/