How to Achieve Maximum File Compression Using the Linux xz Command

When you need to compress massive files—like raw database dumps, ISO images, or uncompressed log files—standard tools like gzip or bzip2 often leave the resulting archive larger than you might want, consuming valuable disk space and network bandwidth. For the absolute maximum compression ratio available in the standard Linux toolkit, system administrators rely on the xz command. xz uses the advanced LZMA2 algorithm to shrink files significantly smaller than its older competitors, though it does require more CPU power and time to achieve those results.

Basic File Compression with xz

Using xz is incredibly straightforward. To compress a single file, you just run the command followed by the name of the file you wish to compress.

xz huge_database.sql

When you execute this command, two things happen: first, xz will spend a few moments crunching the data. Second, it will replace the original huge_database.sql file with a new, highly compressed file named huge_database.sql.xz. The original, uncompressed file is automatically deleted.

How to Keep the Original File

If you are compressing a critical file and you do not want xz to delete the original uncompressed version after it finishes its work, you must use the -k (keep) flag.

xz -k important_document.txt

After running this, you will have both important_document.txt and the new important_document.txt.xz sitting in your directory.

Adjusting the Compression Level

xz operates on a scale from 0 to 9, dictating how hard the CPU should work to shrink the file.

  • Level 6 is the default. It offers an excellent balance between a high compression ratio and reasonable memory usage.
  • Level -0 through -3 are very fast but offer less compression.
  • Level -9 provides extreme, maximum compression. It will make the file as small as mathematically possible, but it is incredibly slow and will consume a massive amount of system RAM during the compression process.

To force maximum compression on an archive, use the -9 flag:

xz -9 backup_archive.tar

How to Uncompress an xz File

When you need to restore the file to its original, usable state, you use the -d (decompress) flag, or you can use the built-in alias unxz.

xz -d huge_database.sql.xz

Just like the compression process, decompressing the file will automatically delete the .xz archive and leave you with only the original, uncompressed file, unless you also include the -k flag.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.