Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: One-liner to exit with the opposite status of a grep command?

How can I reduce the following bash script?

grep -P "STATUS: (?!Perfect)" recess.txt && exit 1 exit 0 

It seems like I should be able to do it with a single command, but I have a total of 3 here.

My program should:

  • Read recess.txt
  • Exit 1 (or non-zero) if it contains a line with "STATUS: " of NOT "Perfect"
  • Exit 0 if no such line exists (i.e. all "STATUS: " lines are "Perfect")

The answer award goes to the tightest script. Thanks!

Example files

Program should have exit status 0 for this file:

FILE: styles.css  STATUS: Perfect!  FILE: contour-styles.css STATUS: Perfect! 

Program should have exit status 1 (or non-zero) for this file:

FILE: styles.css  STATUS: Perfect!  FILE: contour-styles.css STATUS: Busted  FAILURES: 1 failure  Id's should not be styled        1. #asdf 
like image 319
Sean Adkinson Avatar asked Mar 12 '13 17:03

Sean Adkinson


People also ask

How can I get exit status in grep?

Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent option is used and a line is selected, the exit status is 0 even if an error occurred. Other grep implementations may exit with status greater than 2 on error.

What is exit $?

After a function returns, $? gives the exit status of the last command executed in the function. This is Bash's way of giving functions a "return value." [ 1] Following the execution of a pipe, a $? gives the exit status of the last command executed.

What is exit code 2 in bash?

All of the Bash builtins return an exit status of zero if they succeed and a non-zero status on failure, so they may be used by the conditional and list constructs. All builtins return an exit status of 2 to indicate incorrect usage, generally invalid options or missing arguments.


1 Answers

Just negate the return value.

! grep -P "STATUS: (?!Perfect)" recess.txt 
like image 148
Tgr Avatar answered Sep 17 '22 21:09

Tgr