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

其他回答

在阅读了所有这些不同版本的好答案并为自己解决了问题之后,我认为有一些非常重要的小细节,对于GNU/Linux的普遍使用来说是非常罕见的,这些细节没有得到足够的强调,值得更多的评论。

所以我不打算回答每个情况的问题,相反,试着记下当东西不工作的时候去哪里看。

注意这一点非常重要:

THE ORDER OF THE OPTIONS MATTER: it is not the same put the --exclude before than after the file option and directories to backup. This is unexpected at least to me, because in my experience, in GNU/Linux commands, usually the order of the options doesn't matter. Different tar versions expects this options in different order: for instance, @Andrew's answer indicates that in GNU tar v 1.26 and 1.28 the excludes comes last, whereas in my case, with GNU tar 1.29, it's the other way. THE TRAILING SLASHES MATTER: at least in GNU tar 1.29, it shouldn't be any.

在我的例子中,对于Debian扩展上的GNU tar 1.29,有效的命令是

tar --exclude="/home/user/.config/chromium" --exclude="/home/user/.cache" -cf file.tar  /dir1/ /home/ /dir3/

引语不重要,不管有没有引语都有用。

我希望这对一些人有用。

使用find命令和tar append (-r)选项一起使用。通过这种方式,您可以在一个步骤中向现有的tar中添加文件,而不是两步解决方案(创建文件列表,创建tar)。

find /dir/dir -prune ... -o etc etc.... -exec tar rvf ~/tarfile.tar {} \;

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

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

可能是多余的答案,但我发现它很有用,下面是:

而一个FreeBSD根(即使用csh),我想复制我的整个根文件系统到/mnt,但没有/usr和(显然)/mnt。这是什么工作(我在/):

tar --exclude ./usr --exclude ./mnt --create --file - . (cd /mnt && tar xvd -)

我的全部观点是,有必要(通过使用./)指定tar,将大目录的一部分复制到排除的目录中。

我€0.02

下面的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命令。输出—从列表中排除“一个条目”。斜杠()是'标记的转义字符。