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

By Chris Lamb

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/

$ find b/

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

$ find a

$ find 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.

Chris Lamb is a freelance software developer and the current Debian Project Leader. You can read other posts by me, see software I have written or read more about me. You can also follow me @lolamby.

Planets: ALUG UWCS WUGLUG Debian

Wednesday 24th December 2014

Three comments