仅对目录结构进行tar打包

15

我想复制我的目录结构,但排除文件。在tar命令中是否有选项可以忽略所有文件,只递归地复制目录。

5个回答

18

您可以使用 find 命令获取目录,然后打包它们:

find .. -type d -print0 | xargs -0 tar cf dirstructure.tar --no-recursion

如果您有超过大约10000个目录,请使用以下方法解决xargs的限制:

find . -type d -print0 | tar cf dirstructure.tar --no-recursion --null --files-from -

1
在早期的GNU tar中,显然放置**--no-recursion参数的位置并不重要,它仍然可以工作,而在更当前的版本中,它显然需要在--files-from**选项之前。在从Debian Wheezy升级到包括GNU tar 1.29的Debian Stretch后,我的备份就崩溃了。我相应地编辑了答案。 - Gunter Ohrner
我已经编辑了答案,并将“--no-recursion”移动到“--files-from”之前。 - Tometzky

6

包含空格或其他特殊字符的目录名称可能需要额外注意。例如:

$ mkdir -p "backup/My Documents/stuff"
$ find backup/ -type d | xargs tar cf directory-structure.tar --no-recursion
tar: backup/My: Cannot stat: No such file or directory
tar: Documents: Cannot stat: No such file or directory
tar: backup/My: Cannot stat: No such file or directory
tar: Documents/stuff: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

以下是处理“非常规”目录名称的一些变体:
$ find backup/ -type d -print0 | xargs -0 tar cf directory-structure.tar --no-recursion

使用-print0与find一起使用将以空字符结尾的字符串形式发出文件名; 使用-0,xargs将以同样的方式解释参数。使用空字符作为终止符有助于确保即使是带有空格和换行符的文件名也能被正确解释。
还可以直接从findtar传输结果:
$ find backup/ -type d | tar cf directory-structure.tar -T - --no-recursion

使用-T -(或--files-from -)调用tar将导致它从stdin读取文件名,每个文件名都应以换行符分隔。

为了达到最佳效果,可以与null-terminated字符串选项组合使用:

$ find . -type d -print0 | tar cf directory-structure.tar --null --files-from - --no-recursion

其中,我认为最后一个版本是最强大的,因为它支持不寻常的文件名,并且(与xargs不同)不会在系统命令行大小上固有限制。(见xargs --show-limits


0
for i in `find . -type d`; do mkdir -p /tmp/tar_root/`echo $i|sed 's/\.\///'`; done
pushd /tmp/tar_root
tar cf tarfile.tar *
popd
# rm -fr /tmp/tar_root

0

对于AIX:

tar cvfD some-tarball.tar `find /dir_to_start_from -type d -print` 

0

进入你想要开始的文件夹(这就是为什么我们使用find dot), 在其他地方保存tar文件。我认为如果把它留在那里会出现错误。 要用r而不是c来打tar。我认为用cf可以创建新文件, 并且你只能获得最后一组文件子目录。tar r可以将内容附加到tar文件中。 --no-recursion因为find已经给出了整个文件列表, 所以你不需要递归。

find . -type d |xargs tar rf /somewhereelse/whatever-dirsonly.tar --no-recursion

要检查你得到了什么,可以使用tar tvf /somewhereelse/whatever-dirsonly.tar |more。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接