Cannot get rsync exclude option to exclude dir

James P. picture James P. · Mar 17, 2011 · Viewed 12.5k times · Source

Having an issues with rsync. I'm using rsync as a glorified cp command. I have in a script the following code.

rsync -aL --exclude /path/to/exclude/ --exclude='.*' /source/ /destination

I can get the rsync to exclude any hidden files. Hence the '.*' I cannot get the exclude dir to exclude. I've tried using an '=' sign, surrounding the dir with double quotes, with single quotes. Any help would be greatly appreciated. Thanks in advance.

Answer

DanielSmedegaardBuus picture DanielSmedegaardBuus · Aug 15, 2013

Actually, neither Erik's nor Antoni's answers are fully accurate.

Erik is halfway right in saying that

As test/a is the base directory synced from, the exclude pattern is specified by starting with a/

It is true that the exclude pattern's root is test/a (i.e. the pattern /some/path binds to test/a/some/path), but that's not the whole story.

From the man page:

if the pattern starts with a / then it is anchored to a particular spot in the hierarchy of files, otherwise it is matched against the end of the pathname. This is similar to a leading ^ in regular expressions. Thus "/foo" would match a file named "foo" at either the "root of the transfer" (for a global rule) or in the merge-file's directory (for a per-directory rule).

We can ignore the per-directory bit as it doesn't apply to us here.

Therefore, rsync -nvraL test/a test/dest --exclude=a/b/c/d will most definitely exclude test/a/b/c/d (and children), but it'll also exclude test/a/other/place/a/b/c/d.

rsync -nvraL test/a test/dest --exclude=/b/c/d, on the other hand, will exclude only test/a/b/c/d (and children) (test/a being the point to which / is anchored).

This is why you still need the anchoring inital slash if you want to exclude that specific path from being backed up. This might seem like a minor detail, and it will be so the more specific your exclude pattern becomes (e.g. Pictures vs. home/daniel/Pictures) but it might just come around to bite you in the butt.