如何从stdin构建tar?


Answers:


105

就像是:

tar cfz foo.tgz -T -

但是请记住,这不适用于所有可能的文件名;您应该考虑该--null选项并tar从中获取find -print0。(该xargs示例不适用于大型文件列表,因为它将生成多个tar命令。)


“ -T”选项在HP-UX上不可用。
彼得·莫滕森

@PeterMortensen安装gnu tar或bsd tar?您需要在HP-UX应用商店上检查它的名字...
Yogesch '18

需要注意的是,如果你想通过管道sort使用时find-print0选项tar--null选项所描述的,你也将需要提供的-z选项sort
史蒂夫·乔根森

23

正如geekosaur所指出的那样,无需将管道输出find到,xargs因为可以将管道输出find直接到tarusing find ... -print0 | tar --null ...

请注意,尽管gnutarbsdtar排除存档文件之间存在些许差异。

# exclude file.tar.gz anywhere in the directory tree to be tar'ed and compressed
find . -print0 | gnutar --null --exclude="file.tar.gz" --no-recursion -czf file.tar.gz --files-from -
find . -print0 | bsdtar --null --exclude="file.tar.gz" -n -czf file.tar.gz -T -

# bsdtar excludes ./file.tar.gz in current directory by default
# further file.tar.gz files in subdirectories will get included though
# bsdtar: ./file.tar.gz: Can't add archive to itself
find . -print0 | bsdtar --null -n -czf file.tar.gz -T -

# gnutar does not exclude ./file.tar.gz in current directory by default
find . -print0 | gnutar --null --no-recursion -czf file.tar.gz --files-from -

如果在当前目录中找到,那么仅使用../file.tar.gz作为目的地就足够了。
JohanBoulé2016年

是“ gnutar”和“ bsdtar”文字吗?
彼得·莫滕森

16

扩展geekosaur答案

find /directory | tar -cf archive.tar -T -

您可以将stdin与该-T选项一起使用。

请注意,如果-name通常使用某种条件(例如,选项)过滤文件,则需要排除管道中的目录,否则tar将处理它们的所有内容,这不是您想要的。因此,使用:

find /directory -type f -name "mypattern" | tar -cf archive.tar -T -

如果不使用-type"mypattern"将添加所有与目录匹配的内容!


我认为这种方法比其他方法更好,因为您可以将输出到stdout的所有内容通过管道传输
daks 2013年

您可能需要考虑使用来具体说明文件类型find。具体来说,我会做find -type f。这将排除符号链接,字符设备等。如果您对空目录感兴趣,则不要使用find -type f -o -type d
JamesThomasMoon1979年

@ JamesThomasMoon1979,不是更好的选择find -path dir/to/exclude -prune吗?而不是避免dir by type f?而且,你说的mypattern,而不是拍打而是globbin,用于模式比较好find -regex "patter"
牧夫

4

除了使用管道外,还可以使用反引号,例如:

tar cvzf archive.tgz `ls -1 *`

代替ls -1 *您可以放置​​任何其他命令,这些命令会生成需要归档文件的列表


12
唯一的问题是,如果ls命令的输出长于shell允许的最大命令行大小,则此操作将无效。在这种情况下,您必须按照其他答案之一所述进行操作。允许列表任意长。此外,“ find [...] -print0”允许您创建一个包含具有特殊字符的成员的tar文件,而ls方法则没有。这种方法并不安全或普遍适用。
迈克尔·特劳施


1

tar程序已通过多种方式实施。例如,在IBM Unix版本AIX上tar使用-L选项而不是-T,并且需要一个文件而不是允许-指示stdin:

Usage: tar -{c|r|t|u|x} [ -BdDEFhilmopRUsvwZ ] [ -Number ] [ -f TarFil e ]
       [ -b Blocks ] [ -S [ Feet ] | [ Feet@Density ] | [ Blocksb ] ]
       [ -L InputList ] [-X ExcludeFile] [ -N Blocks ] [ -C Directory ] File ...
Usage: tar {c|r|t|u|x} [ bBdDEfFhilLXmNopRsSUvwZ[0-9] ] ]
       [ Blocks ] [ TarFile ] [ InputList ] [ ExcludeFile ]
       [ [ Feet ] | [ Feet@Density ] | [ Blocksb ] ] [-C Directory ] File ...
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.