opyebGlobLab

The rsync include/exclude first-match trap

Rsync · 6 min read

In one line: Rule order in rsync, directory pruning, and a filter order that survives backups, with broken and fixed examples.

rsync filters run the opposite way to .gitignore. The list is scanned from the top, the first matching rule stops the scan, and its action (include or exclude) applies immediately. Order is the whole result, and an include below a catch-all exclude can never be reached.

Broken list, fixed list

# broken: - * swallows everything first
- *
+ /dist/
+ /dist/***

# correct: includes first, catch-all exclude last
+ /dist/
+ /dist/***
- *

The first list transfers nothing under dist, because every path matches the first rule. The debugger reports “the rule on line 2 (+ /dist/) never applies because line 1 matched first”.

No directory, no files inside it

rsync descends the tree before deciding. If a directory is excluded, files inside it are not transferred even when a separate include matches them.

+ /data/report.csv
- /data/

report.csv is included by a file rule, but the parent data is excluded, so nothing is copied. Allow the directory as well.

+ /data/
+ /data/report.csv
- /data/*
- *

A filter order that survives

  1. Most specific includes first: + /keep/, + /keep/***.
  2. Then narrow excludes: - *.tmp.
  3. The catch-all exclude last: - *.

/keep/*** matches the directory and everything inside it; /keep/** matches only the contents, which is why the directory rule is usually written separately.

Dry run first

Before copying, run rsync -avn --itemize-changes --filter='merge .rsync-filter' src/ dest/. -n makes it a dry run and --itemize-changes prints what each item would do. With --delete, a single misplaced rule can delete files at the destination, so the dry run is not optional.

Slash rules

A pattern without a slash is compared with the last path component, so *.log excludes logs at any depth. A leading slash anchors to the transfer root, and a trailing slash applies to directories only.

Put the same rules and paths into the debugger to see the winning line and the traps immediately.

Open GlobLab

Frequently asked questions

Why do includes have to come first?

rsync stops at the first match, so an include must appear above the catch-all exclude to be reachable.

Is the command-line order the same?

Yes. Filters are chained in the order given, which is why managing them in a filter file is less error-prone.

What is the difference between `***` and `**`?

*** matches a directory and everything under it; ** crosses slashes but does not match the directory itself.

Sources

Read next

0 bytes of your input sent to a server (advertising and affiliate widgets excluded)