linuxbashshellrsync

rsync copy over only certain types of files using include option


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

Solution

  • 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="*/" --include="*.sh" --exclude="*" "$from" "$to" 
    

    For rsync versions below 3.0.6, the order needs to be modified as follows (see comments):

    rsync -zarv  --include "*/" --exclude="*" --include="*.sh" "$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