rsync not copying files when using –include flag

I have the following files:


I’d like to copy all abc.txt files and preserve the directory tree. I tried the following command:

rsync -R -P -a -m --include='*/*/abc.txt' remote@server:/target/directory

but this doesn’t copy any files. Any ideas? Would be much appreciated.


Asked By: maia


Try rsync -R -P -a -m --include='*/' --include='abc.txt' --exclude='*' source/ remote@server:/target/directory, where the added source/ is the source parent directory.

It’s still better to specify the actual path to the source parent directory (ether relative or absolute) like source/ or /full/path/to/source. The -a option implies -r which recurses the subdirectories. It’s much better than relying on the shell glob * which can expand to multiple other directories under the current working directory and yield unexpected outcomes. You were confused by how rsync didn’t complain when there is only a target directory and no source directory. This is so that it can support uses cases of the shopt -s nullglob where the * expands to nothing. But if you only add the source directory, it not only copies the wanted files but other files as well.

rsync‘s include syntax is weird. You need to add an --exclude='*' after your --include='*/*/abc.txt' to get it to copy only the files you want. But that causes nothing to be copied because the directories are excluded, so you need to fix that with --include='*/'. Empty directories are correctly excluded because you have -m.

A shorter version of the above command is rsync -RPamf '+ abc.txt' -f 'H,! */' source/ remote@server:/target/directory.

Answered By: Daniel T
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.