2

rsync 排除文件和目录

 1 year ago
source link: https://www.myfreax.com/how-to-exclude-files-and-directories-with-rsync/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

rsync 排除文件和目录

Rsync是一种快速同步的命令行程序,用于在两个计算机之间同步文件和文件夹

Updated At 21 Dec 2022 3 min read
By myfreax
rsync 排除文件和目录

Rsync 排除文件和目录

Rsync是一种快速同步的命令行程序,用于在两个计算机之间同步文件和文件夹。借助Rsync,您可以镜像数据,创建增量备份。

在系统之间复制文件或者复制数据时,您可能要根据它们的名称或位置排除一个或多个文件或目录。

在本教程中,我们将向您展示如何使用rsync排除文件和目录。并介绍--exclude-from,--exclude,--include选项的用法。

并举例说明它们之间区别于关系,比如排除指定文件,排除指定目录,排除多个文件或目录,根据模式排除多个文件或目录,还有选项之间的优先级等。

您应该了解如何使用rsync。在下面的示例中,我们将rsync命令的-a选项一起使用。

rsync命令将会递归同步目录,传输特殊设备和块设备,并保留符号链接,修改时间,组,所有权和权限。排除文件或目录时,需要使用它们到源目录的相对路径。

有两个选项可以指定要排除的文件和目录,当使用rsync命令的--exclude选项时直接指定要排除的目录与文件。

当使用--exclude-from选项时,这将从文件读入要排除的文件与目录。使用那个选项具体取决于你的喜好。

要排除指定文件,请将文件的相对于源目录的路径传递给--exclude选项。

例如参数--exclude 'file.txt' src_directory/将会排除src_directory/file.txt文件。

rsync -a --exclude 'file.txt' src_directory/ dst_directory/

排除指定目录与排除文件相同,只需将目录相对源目录的路径传递给--exclude选项。

如果要排除目录内容,但不排除目录本身,请使用dir1/*而不是dir1

rsync -a --exclude 'dir1' src_directory/ dst_directory/

rsync -a --exclude 'dir1/*' src_directory/ dst_directory/

排除多个文件目录

要排除多个文件或目录,只需指定多个--exclude选项。如果您想使用单个--exclude选项,则可以用大括号{}列出要排除的文件和目录并用逗号分隔。

rsync -a --exclude 'file1.txt' --exclude 'dir1/*' --exclude 'dir2' src_directory/ dst_directory/
rsync -a --exclude={'file1.txt','dir1/*','dir2'} src_directory/ dst_directory/

如果要排除的文件或目录数量很大,则可以在一个文件中列出要排除的文件与目录,然后将文件传递给--exclude-from选项。

rsync -a --exclude-from='exclude-file.txt' src_directory/ dst_directory/
file1.txt
dir1/*
dir2
exclude-file.txt

根据模式排除多个文件或目录

借助rsync,您还可以根据与文件或目录名称匹配的模式排除文件与目录。例如参数--exclude '.jpg'排除所有.jpg文件。

rsync -a --exclude '*.jpg*' src_directory/ dst_directory/

假设您要排除其它的文件和目录,但以.jpg结尾的文件除外。一种选择是指定参数--include='.jpg' --exclude='*'

在使用多个include/exclude选项时,rsync命令将应用第一个匹配规则。

例如参数--include='.jpg' --include='/' --exclude='*'--include='/'不会被rsync应用

rsync -a -m --include='*.jpg' --include='*/' --exclude='*' src_directory/ dst_directory/

另一个选择是将Find命令的标准输出通过管道传递给rsync命令。-printf %P\\0\\n-从文件路径中删除src_directory/

--files-from=-表示仅包含来自标准输入的文件,也就是从find命令传递的文件。-表示标准输入。

find src_directory/ -name "*.jpg" -printf %P\\0\\n | rsync -a --files-from=- src_directory/ dst_directory/

至此,您学习如何在Linux使用rsync命令排除文件和目录。如有任何疑问,请随时发表评论。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK