Unix Compression – How to Create Tar Archive with XZ Compression

archivecompressiontarunix

I'd like to create a tarball using the xz compression tool. According to google, as of 10.10 there is an undocumented "–xz" switch for tar but I can't get it to work. On linux there is a "-J" switch that allows for xz compression but that isn't supported directly on OS X.

The man page for tar references xz compression but does not show a working example of how to use it. My other searches all result in something similar to:

    tar cf - some_dir | xz -1 > some_dir.txz

However, decompressing that from the command line is less than intuitive and requires xz to handle the decompression before handing the file off to tar.

So, what's the "state of the art" in using xz compression directly from tar?

Best Answer

Looking at the source code for the libarchive package from Apple Open Source for OS X 10.8.5, 10.9, 10.10, and macOS 10.12.3, of which contains the source code for bsdtar, it includes the ability to use xz compression directly in tar, however it was not implemented at compile time until OS X 10.9.0 and later. Although the manual page bsdtar.1 doesn't show the -J, --xz options even though it's in the bsdtar.c source code.

To create an xz compressed tar archive in OS X 10.9 or later use the following syntax examples:

tar -cJf filename.tar.xz /path/to/folder_or_file ...

Or:

tar --xz -cf filename.tar.xz /path/to/folder_or_file ...

Example:

tar -cJf Documents.tar.xz "$HOME/Documents"

Or:

tar --xz -cf Documents.tar.xz "$HOME/Documents"

I also checked the Documents.tar.xz file after it was created in a Hex Editor and it did have the proper header which included the expected 7zXZ portion of the signature.