How To Exclude Files and Directories In Rsync?

The rsync is a command-line tool that is used to copy and synchronize files and folders over the network connection. It is very fast and versatile which makes it from other command-line tools. The rsync tool provides a lot of features for sync and copy operation where one of them is excluding files and directories. In this tutorial, we will learn how to exclude files, exclude directories, exclude multiple files and directories, exclude specific extensions.

Exclude Specific File

A specific single file can be excluded from the sync or copy operation. The –exclude option is used by providing the file. Also, the -a option is used for recursive sync or copy.

rsync -a --exclude 'file.txt' /home/ismail /mnt/disk

Exclude Specific Directory

A specific directory can be also excluded from the sync or copy operation. The –exclude option is used to specify the directory name. In the following example we will exclude the directory named “mydir” like below.

rsync -a --exclude 'mydir' /home/ismail /mnt/disk

Alternatively the directory contents can be excluded by the directory itself remains. The glob * is used to specify the directory content. The “mydir/*” is used to exclude the contents of the “mydir” but not itself.

rsync -a --exclude 'mydir/*' /home/ismail /mnt/disk

Exclude Multiple Files and Directories

The –exclude option can be used multiple times in order to exclude multiple files and directories. In the following example we will exclude the files named “file.txt“, “myfile.xls“, and directories “mydir” and “yourdir“.

rsync -a --exclude 'mydir' --exclude 'yourdir' --exclude 'file.txt' --exclude 'myfile.xls' /home/ismail /mnt/disk

Multiple files and directories can be excluded for the rsync command by using the following syntax. Files and folders is specified inside a curly brackets.

--exclude={ITEM,ITEM,ITEM,...}

The example is like below.

rsync -a --exclude={'mydir','yourdir','file.txt','myfile.xls'} /home/ismail /mnt/disk

Exclude Specific File Extension

Another popular use case for the rsync exclude is providing a specific file extension for exclude. The file extension can be specified with the glob operators. In the following example we will do not sync the mp3 files by using the “*.mp3”.

rsync -a --exclude '*.mp3' /home/ismail /mnt/disk

Exclude Specified File or Directory Names

Also, the file names can be specified as patterns in order to exclude them from copy or sync. The file or directory name is not specified completely and only some pattern or part is specified. For example “my*” can be used to exclude files and directories where their names start with “my” is excluded.

rsync -a --exclude 'my*' /home/ismail /mnt/disk

Leave a Comment