How can I exclude all “permission denied” result lines from “grep”?

Viewed 44763

So, the thing is, I'm on linux terminal using grep command and I want the output without all the lines where it prints at the beginning "grep:" or the lines that begins with "./", because now I'm getting something like this:

grep: ./users/blabla1: Permission denied
grep: ./users/blabla2: Permission denied
grep: ./users/blabla3: Permission denied
grep: ./users/blabla4: Permission denied
grep: ./users/blabla5: Permission denied
grep: ./users/blabla6: Permission denied
grep: ./users/blabla7: Permission denied
grep: ./users/blabla8: Permission denied
./foo/bar/log.log
./foo/bar/xml.xml

I have tried this:

grep -irl "foo" . | grep -v "Permission denied"

I have also tried this one:

 grep -irl "foo" . | grep -v "^grep:"

And finally this one:

 grep -irl "foo" . | grep "^./"

But I keep getting same results as if I haven't put anything after the |, any ideas? What am I missing?

3 Answers

I prefer to use the -s 'suppress' flag:

grep -irls "foo"

Note the "Portability note" from the grep man page:

-s, --no-messages

Suppress error messages about nonexistent or unreadable files. Portability note: unlike GNU grep, 7th Edition Unix grep did not conform to POSIX, because it lacked -q and its -s option behaved like GNU grep's -q option. USG-style grep also lacked -q but its -s option behaved like GNU grep. Portable shell scripts should avoid both -q and -s and should redirect standard and error output to /dev/null instead. (-s is specified by POSIX.)

Going off of your first try:

grep -irl "foo" . | grep -v "Permission denied"

You're just missing the operator to redirect standard error. '|' redirects standard output. if you add '&', you will also redirect standard error, which is what is giving you the "Permission denied" message. Try:

grep -irl "foo" . &| grep -v "Permission denied"

This works for me, because for some reason my machine doesn't like the "2> /dev/null" option.

Related