Rsync: How to Exclude All Directories Except a Few

rsync

There appear to be a lot of SF and SO questions out there about this, but none seem to match my requirements.

source_dir/
  some_dir/
  another_dir/
  some_file.php
  some_other_file.txt
  include_this_dir/
  include_that_dir/
  yet_another_dir/

So I want to rsync two of those dirs, while excluding the rest. It's important that we exclude all but those two dirs, because there might be other files that at some later date are added to the source_dir and would need to be excluded without being explicitly listed.

I tried:

rsync -av --dry-run --delete --exclude="source_dir/*" (or just "*") --include-from="include.txt" source_dir dest_dir

And my include.txt had

  include_this_dir/
  include_that_dir/

and also I tried adding

  source_dir/

No joy. Nothing gets included at all.

Best Answer

A simple filter should do the trick. To build on the prior answer with a proper example -- Explicitly include the parent(s), plus all (**) sub folders and files. Then exclude everything else. Here's filter.txt:

+ /include_this_dir/
+ /include_this_dir/**
+ /include_that_dir/
+ /include_that_dir/**
- /**

With the command line:

rsync -av --dry-run --filter="merge filter.txt" source_dir/ dest_dir/

Would result in:

sending incremental file list
created directory dest_dir
./
include_that_dir/
include_that_dir/somefile.txt
include_that_dir/subdir/
include_this_dir/

sent 202 bytes  received 65 bytes  534.00 bytes/sec
total size is 0  speedup is 0.00 (DRY RUN)