You can use cp -a to copy directory trees, but rsync can do the same and give you more flexibility. rsync supports a syntax for filter rules which specify which files and directories should and should not be copied.
Examples
Copy only the directory structure without copying any files:
$ rsync -a -f"+ */" -f"- *" source/ destination/
The two -f arguments mean, respectively, "copy all directories" and then "do not copy anything else".
Copy only directories and Python files:
$ rsync -a -f"+ */" -f"+ *.py" -f"- *" source/ destination/
This is really handy for replicating the general directory structure but only copying a subset of the files.
Copy everything but exclude .git directories:
$ rsync -a -f"- .git/" -f"+ *" source/ destination/
Conclusion
Of course, rsync also works great for copying files between machines, and it knows better than to transfer files that already exist on the destination. I use something similar to the above to do backups, copying my homedir but excluding stuff like caches that are not even worth copying.
Very good examples. Thank you.
ReplyDeleteFirst, thanks :)
ReplyDeleteSecond, how can I have it copy all directories under /var/www but exclude all files under /var/www ; recursively...
PERFECT. Been looking this for a while.
ReplyDeleteThanks for the tip! Just used this today.
ReplyDeleteShai, you replace "source/" and "destination/" with:
ReplyDelete/var/www/ /some/directory/
/var/www/ somemachine:/some/directory/
thnx for tip very helpful
ReplyDeleteExcellent. Rsyncing the directory structure only was exactly what I needed!
ReplyDeleteThanks for the tip Phil!
ReplyDeleteFor those who have an older version of rsync (one that doesn't support -f), you can do the same thing with --include and --exclude.
So Phil's example becomes:
$ rsync -a --include=*/ --exclude=* source/ destination/
-klam
Excellent thanks!
ReplyDeleteI have a question. I tried to use the syntax above under rsync 3.0.9 with the following results (source and dest names changed to protect the not-so-innocent):
ReplyDeletersync -v -f"+ */" -f"- *" /source desthost:/dest
skipping directory source
rsync -v -f"+ */" -f"- *" /source/ desthost:/dest/
skipping directory .
Am I missing something, or did the behavior change in 3.0.9?
Found the trick. I had to use -r to recurse the tree.
ReplyDeletersync -v -a -r -f"+ */" -f"- *"