How do I compress multiple files into a .xz archive?

I want to compress several images into a .xz archive. How do I do that?


Solution 1:

Use tar with -J option:

tar -cvJf images.tar.xz /directory/containing/images/*

tar is used to combine multiple files into one (Archive) and then we need to compress the archive using XZ compression algorithm.

From man tar:

-c, --create
       create a new archive
-v, --verbose
       verbosely list files processed
-J, --xz

-f, --file ARCHIVE
       use archive file or device ARCHIVE

Also note that images.tar.xz will be created in the current directory, if you want to save it somewhere else use /full/path/to/images.tar.xz.

Solution 2:

Although tar cJf archive files... as detailed by Zacharee1 and by heemayl is usually what you'll want to do, another way is to pipe tarred data to the xz command:

tar c files... | xz > archive.tar.xz

Since Ubuntu's tar supports the J option, this alternate way is specifically useful when you wish to pass options to xz.

In this example, I tar and xzip some TIFF files with a high level of compression (-9 to xz) and verbose output (v to tar, -v to xz):

ek@Io:~/Pictures$ tar vc *.tif{,f} | xz -9v > pics.tar.xz
page001.tif
page002.tif
page003.tif
page004.tif
page9087.tif
page3la.tiff
quux0000.tiff
  100 %       207.3 KiB / 290.0 KiB = 0.715

This could, of course, also be done in two explicitly separate steps:

ek@Io:~/Pictures$ tar vcf pics.tar *.tif{,f}
page001.tif
page002.tif
page003.tif
page004.tif
page9087.tif
page3la.tiff
quux0000.tiff
ek@Io:~/Pictures$ xz -9v pics.tar
pics.tar (1/1)
  100 %       207.3 KiB / 290.0 KiB = 0.715

Those two ways are not actually equivalent in how they operate, though the .tar.xz files they produce in the end should be the same (and were, when I tested it).

  • In the first, the output of tar is piped (|) to the input of xz. xz receives data from tar almost immediately, and no intermediate uncompressed tar file is ever created. This is to say that the first way is essentially equivalent to tar cJf archive files..., except for the additional arguments passed to xz.
  • In the second, an uncompressed tar archive is created by the first command, then compressed by xz in the second command. (xz automatically deletes the original file when it's done, unless invoked with -k/--keep.)

For further reading, see this post by Rafael van Horn and the tar and xz manpages.