1. Overview

The Linux rsync command-line utility allows us to copy and delete files on disk. In this tutorial, we’ll see how to provide the command with options that allow us to copy only certain types of files.

2. rsync

Generally, we use rsync to synchronize source and destination directories on Linux filesystems. These directories are either local to our host or located on a remote host.

Ultimately, to achieve equality, the command will copy only the portions of each file required either to or from one location to the next, depending on how we run it. For this reason, rsync is often the preferred way to transfer files because it moves a minimal amount of data. Consequently, this can make copying files to remote hosts very fast.

3. Using the include Option

In the case where we want to limit the files transferred by rsync we can utilize the include command-line option. As its name implies, this option will filter the files transferred and include files based on the value provided. However, the include option only works along with the exclude option. This is because the default operation for rsync is to include everything in the source directory.

Let’s say we only want to transfer text files in the current directory. We would only need to provide the include filter and use exclude with the wildcard character:

rsync --include=*.txt --exclude=* /source/* /destination/

Here, the order of our options is very important. Both options are filters and they are applied in order. So, we have to first use the filter that represents the files we want and then exclude everything. When applied this will mean that all text files are selected for transfer, then any other files are excluded.

Now, if we want to transfer text and log files we have to use an include option for each, again before the exclude option:

rsync --include=*.txt --include=*.log --exclude=* /source/* /destination/

Finally, to transfer all files that match in all our sub-directories we tell the command to recurse using the -a and -r options:

rsync -ar --include=*/ include=*.txt --exclude=* /source/* /destination/

However, this has the potential of copying all the sub-directories (with no files), so we must also use the —prune-empty-dirs or -m option to prevent this from occurring:

rsync --ar --prune-empty-dirs --include=*/ include=*.txt --exclude=* /source/* /destination/

4. Versions and Variants

This tutorial is based on version 3.2.3. The latest version of rsync is always available at https://rsync.samba.org.

The order of the include and exclude filter options, and how they are applied depends on the version. Earlier versions may not process files as described in this tutorial. However, versions after 3.0.5 should run as we expect.

5. Conclusion

In this article, we saw how to use the include option to filter the files transferred when using rsync.

guest
0 Comments
Inline Feedbacks
View all comments