rsync copy over only certain types of files using include option

user881480 picture user881480 · Jun 20, 2012 · Viewed 98k times · Source

I use the following bash script to copy only files of certain extension(in this case *.sh), however it still copies over all the files. what's wrong?

from=$1
to=$2

rsync -zarv  --include="*.sh" $from $to

Answer

chepner picture chepner · Jun 20, 2012

I think --include is used to include a subset of files that are otherwise excluded by --exclude, rather than including only those files. In other words: you have to think about include meaning don't exclude.

Try instead:

rsync -zarv  --include "*/" --exclude="*" --include="*.sh" "$from" "$to"

For rsync version 3.0.6 or higher, the order needs to be modified as follows (see comments):

rsync -zarv --include="*/" --include="*.sh" --exclude="*" "$from" "$to"

Adding the -m flag will avoid creating empty directory structures in the destination. Tested in version 3.1.2.

So if we only want *.sh files we have to exclude all files --exclude="*", include all directories --include="*/" and include all *.sh files --include="*.sh".

You can find some good examples in the section Include/Exclude Pattern Rules of the man page