是否有一个简单的shell命令/脚本支持排除某些文件/文件夹的归档?

我有一个需要归档的目录,其中有一个子目录,其中有许多非常大的文件,我不需要备份。

不完全是解决方案:

tar——exclude=PATTERN命令匹配给定的模式并排除那些文件,但我需要忽略特定的文件和文件夹(完整的文件路径),否则有效的文件可能会被排除。

我还可以使用find命令创建一个文件列表,排除我不想存档的文件,并将该列表传递给tar,但这只适用于少量文件。我有成千上万。

我开始认为唯一的解决方案是创建一个包含要排除的文件/文件夹列表的文件,然后使用rsync with——exclude-from=file将所有文件复制到tmp目录,然后使用tar对该目录进行归档。

谁能想到更好/更有效的解决办法?

编辑:查尔斯·马的解决方案很有效。最大的问题是——exclude='。/folder'必须在tar命令的开头。完整命令(先cd,所以备份相对于该目录):

cd /folder_to_backup
tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .

当前回答

这个排除模式处理文件名后缀(如png或mp3)以及目录名(如.git和node_modules)

tar --exclude={*.png,*.mp3,*.wav,.git,node_modules} -Jcf ${target_tarball}  ${source_dirname}

其他回答

最好的方法是通过xargs(处理大量的参数)与tar一起使用find。例如:

find / -print0 | xargs -0 tar cjf tarfile.tar.bz2

为了避免可能的'xargs:参数列表太长'错误,由于使用find…| xargs…当处理成千上万的文件时,您可以使用find…将find的输出直接输送到tar。-print0 | tar——null ....

# archive a given directory, but exclude various files & directories 
# specified by their full file paths
find "$(pwd -P)" -type d \( -path '/path/to/dir1' -or -path '/path/to/dir2' \) -prune \
   -or -not \( -path '/path/to/file1' -or -path '/path/to/file2' \) -print0 | 
   gnutar --null --no-recursion -czf archive.tar.gz --files-from -
   #bsdtar --null -n -czf archive.tar.gz -T -

这个排除模式处理文件名后缀(如png或mp3)以及目录名(如.git和node_modules)

tar --exclude={*.png,*.mp3,*.wav,.git,node_modules} -Jcf ${target_tarball}  ${source_dirname}

我同意——exclude标志是正确的方法。

$ tar --exclude='./folder_or_file' --exclude='file_pattern' --exclude='fileA'

我要提醒大家的是,我并没有发现明显的副作用: 在本例中排除'fileA'将递归地搜索'fileA' !

示例:一个包含同名文件(data.txt)的单子目录的目录

data.txt
config.txt
--+dirA
  |  data.txt
  |  config.docx

如果使用——exclude='data.txt',存档将不包含data.txt文件。如果对第三方库(比如node_modules目录)进行归档,可能会导致意想不到的结果。 为了避免这个问题,请确保给出整个路径,比如——exclude='./dirA/data.txt'

可以使用cpio(1)创建tar文件。Cpio将文件归档到stdin上,所以如果你已经找到了你想要使用的find命令来选择存档文件,那么将它导入Cpio来创建tar文件:

find ... | cpio -o -H ustar | gzip -c > archive.tar.gz