Shell – rsync recursively with a certain depth of subfolders

directoryrecursiversyncshell

I want to rsync a folder recursively but want subfolders included only to a certain depth.

For example I would want a depth of 1,2,3 or 4 subfolders like this:

source/
├── subfolder 1
│   ├── subsubfolder
│   │   ├── subsubsubfolder
│   │   │   └── wanted with depth 4.txt
│   │   └── wanted with depth 3.txt
│   └── wanted with depth 2.txt
├── subfolder 2
│   └── wanted with depth 2.txt
└── wanted with depth 1.txt

Best Answer

Facilitate the --exclude= option.

To sync to a depth of 2 (files within folder and subfolders):

rsync -r --exclude="/*/*/" source/ target/

It will give you this:

target/
├── subfolder 1
│   └── wanted with depth 2.txt
├── subfolder 2
│   └── wanted with depth 2.txt
└── wanted with depth 1.txt

To sync to a depth of 3 (files within folder, subfolders and subsubfolders):

rsync -r --exclude="/*/*/*/" source/ target/

will give you:

target/
├── subfolder 1
│   ├── subsubfolder
│   │   └── wanted with depth 3.txt
│   └── wanted with depth 2.txt
├── subfolder 2
│   └── wanted with depth 2.txt
└── wanted with depth 1.txt
Related Question