While writing scripts, sometimes you just need to know if a file contains the pattern and act based on the exit status of the command. Instead of redirecting the output to /dev/null you can use the -q option. This will avoid printing anything on stdout and also provides speed benefit as processing would be stopped as soon as the given condition is satisfied.

$ cat find.txt
The find command is more versatile than recursive options and
and extended globs. Apart from searching based on filename, it
has provisions to match based on the the file characteristics
like size and time.

$ grep -wE '(\w+) \1' find.txt
has provisions to match based on the the file characteristics
$ grep -qwE '(\w+) \1' find.txt
$ echo $?
0

$ grep -q 'xyz' find.txt
$ echo $?
1

$ grep -qwE '(\w+) \1' find.txt && echo 'Repeated words found!'
Repeated words found!

The -s option will suppress the error messages that are intended for the stderr stream.

# when the input file doesn't exist
$ grep 'in' xyz.txt
grep: xyz.txt: No such file or directory
$ grep -s 'in' xyz.txt
$ echo $?
2

# when sufficient permission is not available
$ touch new.txt
$ chmod -r new.txt
$ grep 'rose' new.txt
grep: new.txt: Permission denied
$ grep -s 'rose' new.txt
$ echo $?
2

Errors regarding regular expressions and invalid options will be on the stderr stream even when the -s option is used.

$ grep -sE 'a(' find.txt
grep: Unmatched ( or \(

$ grep -sE 'a(' find.txt 2> /dev/null
$ echo $?
2

info Check out my ch command line tool for a practical example of using the -q option.

Video demo:


info See my CLI text processing with GNU grep and ripgrep ebook if you are interested in learning about GNU grep and ripgrep commands in more detail.