How to get an empty tar archive?

You can force GNU and BSD tar to create an empty archive with:

tar -cf tarfilename.tar -T /dev/null

If you have GNU tar

Either using /dev/null

$ tar -cf empty.tar --files-from /dev/null

Or by reading EOF from standard input.

$ printf '' | tar -cf empty.tar --files-from -

If you don't have tar

An empty tar file is just a file with 10240 NUL bytes in it. So to create an empty tar file, you don't even need tar but instead can use either of these:

$ head --bytes=10240 /dev/zero > empty.tar
$ truncate --size=10240 empty.tar
$ fallocate --length=10240 empty.tar
$ dd if=/dev/zero bs=10240 count=1 iflag=fullblock > empty.tar
$ dd if=/dev/zero bs=1 count=10240 > empty.tar

Why does this work?

https://www.gnu.org/software/tar/manual/html_node/Standard.html

Physically, an archive consists of a series of file entries terminated by an end-of-archive entry, which consists of two 512 blocks of zero bytes.

At the end of the archive file there are two 512-byte blocks filled with binary zeros as an end-of-file marker.

So in practice, it's sufficient to write 1024 zero bytes (two times 512 byte blocks) into a file to obtain an empty archive:

$ head --bytes=1024 /dev/zero > empty.tar
$ tar tvf empty.tar

If we only write 1023 zeros and a single 'one' into a file, tar will complain because instead of two blocks filled with all zeros, it only found one block with all zeros (the first) while the second was not all zeros:

$ { head --bytes=1023 /dev/zero; printf '\001' } > empty.tar
$ tar tvf empty.tar
tar: A lone zero block at 1

But why not just 1024 zero bytes but 10240 instead? The reason is blocking or the default record size or the blocking factor:

https://www.gnu.org/software/tar/manual/html_section/tar_76.html

The default blocking factor is 20. With a block size of 512 bytes, we get a record size of 10240. And tar will always pad the tarball such that its size is a multiple of the record size:

Some devices requires that all write operations be a multiple of a certain size, and so, tar pads the archive out to the next record boundary.


BSD: tar cvf empty.tar --from-file /dev/null

GNU (Linux): tar cvf empty.tar --files-from /dev/null

Solaris: tar cvf empty.tar -I /dev/null

Tags:

Tar