6

There are some directories that can cause problem with find, and especially find /. These are directories in which the OS creates files which are not really files. Among these directories are /proc /sys /run.

The thing is that if you are doing something like find / -exec grep, you can mess up the system real bad if you crawl some of these systems.

So how can I tell find to skip these directories without listing them. Because someone just may decide to create a new directory like this. Rather then rely on a list I would rather have a test for the directory and an option to exclude directories that fail this test.

Volker Siegel
  • 17,283

2 Answers2

4

Ok, you do not want to rely on a list of excluded files, so you don't risk excluding too few directories.

So let's rely on saying which files to include.

These "not really files" are almost all on separate file systems.
Which are more like "not really file systems", just looking similar.

What we can say, is that they are not on our "real" file systems.
Assuming we have two partitions, mounted in / and `/home':

With the option -xdev, We can run find on these known-good places, and nothing else:

find / /home -xdev -exec grep ...

Some strange files may still be mixed into our normal files (see "almost all" above).

They do indeed cause problems: if there is a forgotten fifo file, and you run grep over it, your grep would try to read from it and just wait forever.

We could exclude all dangerous types, but looking at the possible file types for -type, there are not many of them we really need: f, d, and l for symlinks.
We just need to take care to either include some or all of typed f, d and l, or to exclude b,c,p,s and D.

find / /home -xdev -type f -exec grep ...

or in case we want to include symlinks:

find /home/me/dirWithSomeLinksToFiles -xdev \( -type f -or -type d \) -exec grep ...
Paulo Tomé
  • 3,782
Volker Siegel
  • 17,283
  • This answer assumes that the file might only be on / or /home, but that's a false assumption given that there can be many other mount points, and those mount points can change over time, or across systems. – RonJohn Dec 09 '20 at 05:15
0

Instead of worrying about the directories, why don't you tell find to only feed actual files into grep?

find / -type f -exec grep .... {} +

Seems to work fine for me (grepping kmem won't kill the box ;D).

tink
  • 6,765