hsiu
hsiu

Reputation: 281

grep show all lines, not just matches, set exit status

I'm piping some output of a command to egrep, which I'm using to make sure a particular failure string doesn't appear in.

The command itself, unfortunately, won't return a proper non-zero exit status on failure, that's why I'm doing this.

command | egrep -i -v "badpattern"

This works as far as giving me the exit code I want (1 if badpattern appears in the output, 0 otherwise), BUT, it'll only output lines that don't match the pattern (as the -v switch was designed to do). For my needs, those lines are the most interesting lines.

Is there a way to have grep just blindly pass through all lines it gets as input, and just give me the exit code as appropriate?

If not, I was thinking I could just use perl -ne "print; exit 1 if /badpattern/". I use -n rather than -p because -p won't print the offending line (since it prints after running the one-liner). So, I use -n and call print myself, which at least gives me the first offending line, but then output (and execution) stops there, so I'd have to do something like

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

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

Upvotes: 9

Views: 6010

Answers (3)

Nemo
Nemo

Reputation: 71585

Actually, your perl idea is not bad. Try:

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

I bet this is at least as fast as the other options being suggested.

Upvotes: 7

Seth Robertson
Seth Robertson

Reputation: 31471

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

Upvotes: 3

Fredrik Pihl
Fredrik Pihl

Reputation: 45670

How about doing a redirect to /dev/null, hence removing all 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 simply 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.)

Upvotes: 1

Related Questions