December 24th 2014

find(1), trailing slashes and symbolic links to directories

Here's a nice little "gotcha" in find(1).

First, let's create a directory and a symlink to that directory. We'll add an empty file just underneath to illustrate what is going on:

$ mkdir a
$ ln -s a b
$ touch a/file

If we invoke find with a trailing slash, everything works as expected:

$ find a/
a/
a/file

$ find b/
b/
b/file

... but if we omit the trailing slash, find does not traverse the symlink:

$ find a
a
a/file

$ find b
b

This implies that any normal-looking invokation of find such as:

find /path/to/dir -name 'somefile.ext' ...

... is subtly buggy as it won't accomodate the sysadmin replacing that path with a symlink.


This is, of course, well-covered in the find(1) manpage (spoiler: the safest option is to specify -H, or simply to append the trailing slash), but I would still class this as a "gotcha" because of the subtle difference between the trailing and non-trailing slash variants.

Putting it another way, it's completely reasonable that find doesn't follow symlinks, but when this behaviour based on the presence of the trailing slash—a usually meaningless syntactic distinction—it crosses the rubicon to being counter-intutive.




You can subscribe to new posts via email or RSS.