是否有一个简单的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 .

当前回答

为了避免可能的'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 -

其他回答

您可以使用——exclude来排除tar目录。

如果你想存档除/usr之外的所有内容,你可以使用:

tar -zcvf /all.tgz / --exclude=/usr

对你来说,可能是这样的

tar -zcvf archive.tgz arc_dir --exclude=dir/ignore_this_dir

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

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

下面的bash脚本应该可以做到这一点。它使用了Marcus Sundman给出的答案。

#!/bin/bash

echo -n "Please enter the name of the tar file you wish to create with out extension "
read nam

echo -n "Please enter the path to the directories to tar "
read pathin

echo tar -czvf $nam.tar.gz
excludes=`find $pathin -iname "*.CC" -exec echo "--exclude \'{}\'" \;|xargs`
echo $pathin

echo tar -czvf $nam.tar.gz $excludes $pathin

这将打印出您需要的命令,您可以复制并粘贴回去。可能有一种更优雅的方式直接将它提供给命令行。

只要改变*。CC的任何其他常用扩展名,文件名或正则表达式,你想排除,这应该仍然工作。

EDIT

再补充一点解释;find生成匹配所选正则表达式的文件列表(在本例中为*. cc)。这个列表通过xargs传递给echo命令。输出—从列表中排除“一个条目”。斜杠()是'标记的转义字符。

对于Mac OSX,我必须这么做

tar -zcv——exclude='folder' -f theOutputTarFile.tar folderToTar .tar -zcv——exclude='folder

注意——exclude=后面的-f

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

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