We will show you how you can exclude a file or directory in rsync using different examples. The examples presented here have been tested on Ubuntu 20.04 LTS, however, these are also valid for other Linux distributions having rsync installed.
Exclude a Specific File
While syncing a directory, you may want to exclude a specific file located inside it. You can do so using the –exclude option followed by the filename enclosed in commas.
The syntax of the command will be:
Here, a option is used for recursive syncing.
For instance, to exclude a file named sample.txt from the source when syncing src_dir and dest_dir, the command would be:
Exclude a Specific Directory
To exclude a specific directory (including its subdirectories) from the source when syncing the source and the destination directories, use the following syntax:
For example, to exclude a directory named sampledir when syncing the src_dir and dest_dir, the command would be:
If you want to exclude the content of the directory but not the directory itself, use directory name followed by /*:
The above command will only copy the directory to the destination but not its content.
Exclude Multiple Files or Directories
To exclude multiple files or directories during sync process, specify each of them as follows:
Instead of specifying –exclude option separately for each file or directory, you can use a single –exclude option by specifying all the files or directories in curly brackets.
Another option to exclude multiple files or directories is by listing them in a file and then passing the filename to the –exclude-from option:
Here, the “list” contains the file and directories name that we want to exclude. This command syncs src_dir to the dest_dir while excluding the files and directories mentioned in the “list” file.
Exclude Files or Directories that Match a Pattern
With rsync, you can also exclude files or directories that match a specific pattern. For example, while syncing a directory, you may want to exclude all files ending with a .txt extension. The command, in this case, would be:
Exclude a File by Size
With rsync, you can exclude files based on their minimum or maximum size. Here, we will not use –exclude option, but the –max-size=<size in MB> or –min-size==<size in MB> options based on the maximum and minimum size, respectively.
Here is the listing of our src_dir which shows file names along with their sizes in MB.
Let’s say we want to sync all the files to the dest_dir except those with a size greater than 100MB. In this case, the command would be:
Similarly, to exclude files that are smaller than a specific size, let’s say 50 MB, the command would be:
Conclusion
That is all there is to it! In this post, we have discussed different examples to exclude a file or a directory in rsync. We have shown how to exclude a single file or directory, multiple files and directories, files that match a specific pattern, and the files based on their minimum/maximum sizes.