0

I cannot figure out how to solve this problem. I got a function, and I send to it a directory and a word. I want to search all files in that directory which contain that word, but if I can not read them, I want to print my own error. Here is what I have:

find $1 -type f -print0 | xargs -0 grep "$2" || error 3 "You can not read the archive."

Where:

  • $1 -> Directory
  • $2 -> Word to search.

It works, but the point is that I got the grep error if I find a non-readable file, and I dont want it to appear. Do you know what can I do in order to solve this?

Thank you in advance.

EDIT: Ok and if I use this:

result=$(find $1 -type f -print0 | xargs -0 grep -s "$2" || error 3 "You can not read the archive.")

It only saves the error once, how can I do it if I want to print the error once for every archive?

Soutuyo
  • 106
  • 10
  • You will find your answer here: http://stackoverflow.com/questions/762348/how-can-i-exclude-all-permission-denied-messages-from-find?noredirect=1&lq=1 – codeforester Jan 06 '17 at 19:15

1 Answers1

1

In this case, two options come to mind:

1) Redirect stderr to /dev/null (/dev/null being the null device, which "discards" any input sent to it), for example:

grep "$2" 2> /dev/null

2) If you are using GNU grep, then the option grep -s would work for you, for example:

grep -s "$2"

From the grep manual:

-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 .)

Jamil Said
  • 2,033
  • 3
  • 15
  • 18
  • Thank you very much!! I didn't know grep has that. – Soutuyo Jan 07 '17 at 09:47
  • Ok and if I use this: result=$(find $1 -type f -print0 | xargs -0 grep -s "$2" || error 3 "You can not read the archive.") It only saves the error once, how can I solve this? – Soutuyo Jan 07 '17 at 10:25
  • Since this is a different problem, I suggest that you revert your current question back to the original and after that post a new question with the new problem on SO -- new questions get all the attention and answers from the community. Also, by doing that it would make my answer "make sense" again, since when I answered it there was only the `grep` error problem. – Jamil Said Jan 07 '17 at 19:59