How can I build a tar from stdin?
How can I pipe information into tar
specifying the names of the file?
Solution 1:
Something like:
tar cfz foo.tgz --files-from=-
But keep in mind that this won't work for all possible filenames; you should consider the --null
option and feed tar
from find -print0
. (The xargs
example won't quite work for large file lists because it will spawn multiple tar
commands.)
Solution 2:
As already pointed out by geekosaur, there is no need to pipe the output of find
to xargs
because it is possible to pipe the output of find
directly to tar
using find ... -print0 | tar --null ...
.
Note the slight differences between gnutar
and bsdtar
in excluding the archive file though.
# 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 -
Solution 3:
Extending geekosaur answer:
find /directory | tar -cf archive.tar -T -
You can use stdin with the -T
option.
Note that if you filter files using some condition (e.g. -name
option) in general you need to exclude directories in the pipe, otherwise tar will process all their content, that is not what you want. So, use:
find /directory ! -type d -name "mypattern" | tar -cf archive.tar -T -
If you don't use -type
, all the content of directories matching "mypattern"
will be added !