Use Files to Ignore Directories in Rsync

Miris

<2021-12-07 Tue>

We can tell rsync to skip directories containing files with a specific name. This controls what directories to copy without tweaking our script at all. Ideally, a spiffy filter file should be used, but one or two souls out there may prefer this approach.

For this example, we will use ".rsync-exclude" as the file name. Simply create an ".rsync-exclude" file within each directory that you don't want to be copied, and then adapt the snippet below to your needs:

find "${SOURCE}" -iname "*.rsync-exclude" -printf "%h\n" \
    | xargs -I {} basename "{}" \
    | rsync -aAXHv --exclude-from=- "${SOURCE}" "${TARGET}"

The principle is that we feed rsync a curated list of directories containing the ".rsync-exclude" file. This list would be passed to the –exclude-from=FILE parameter, which in turn tells rsync to ignore files/directories listed in the given FILE (or in this case, the stdin).