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

Just negate the return value.

! grep -P "STATUS: (?!Perfect)" recess.txt

I came across this, needing an onlyif statement for Puppet. As such, Tgr's bash solution wouldn't work, and I didn't want to expand the complexity as in Christopher Neylan's answer.

I ended up using a version inspired by Henri Schomäcker's answer, but notably simplified:

grep -P "STATUS: (?!Perfect)" recess.txt; test $? -eq 1

Which very simply inverts the exit code, returning success only if the text is not found:

  • If grep returns 0 (match found), test 0 -eq 1 will return 1.
  • If grep returns 1 (no match found), test 1 -eq 1 will return 0.
  • If grep returns 2 (error), test 2 -eq 1 will return 1.

Which is exactly what I wanted: return 0 if no match is found, and 1 otherwise.


To make it work with set -e surround it in a sub-shell with ( and ):

$ cat test.sh 
#!/bin/bash

set -ex
(! ls /tmp/dne)
echo Success
$ ./test.sh 
+ ls /tmp/dne
ls: cannot access /tmp/dne: No such file or directory
+ echo Success
Success
$ mkdir /tmp/dne
$ ./test.sh 
+ ls /tmp/dne
$