Why Choose XZ over Gzip?
For decades, gzip has been the undisputed standard for compressing files on Linux. However, modern systems frequently handle massive database dumps, VM images, and log archives where storage space is critical. The xz command uses the LZMA2 compression algorithm. While it requires significantly more CPU power and time to compress a file than Gzip, the resulting archive is substantially smaller, making it the superior choice for long-term archiving and minimizing network transfer sizes.
Step 1: Compress a Single File
The basic syntax of the xz command is incredibly straightforward. To compress a large file (e.g., a SQL database dump), open your terminal and run:
xz database_backup.sql
By default, xz will compress the file, rename it to database_backup.sql.xz, and completely delete the original uncompressed file. If you want to keep the original file, you must use the -k (keep) flag:
xz -k database_backup.sql
Step 2: Adjust the Compression Level
You can explicitly dictate how hard the CPU should work to compress the file by specifying a level from -0 (fastest, least compression) to -9 (slowest, highest compression). The default level is -6.
To force maximum compression on an archive, run:
xz -9 -k database_backup.sql
Note: Using level -9 requires a massive amount of RAM during the compression process. Do not run this on a server with very low memory.
Step 3: Compress Multiple Files Using Tar
A major limitation of the xz command is that, exactly like gzip, it can only compress a single file. It cannot compress entire directories on its own. To compress a folder, you must combine it with the tar command.
Modern versions of tar have built-in support for xz using the uppercase -J flag. To compress the entire /var/log directory into a single archive, run:
tar -cJf logs_archive.tar.xz /var/log/
This command bundles the folder into a tarball (-c for create, -f for file) and simultaneously passes it through the xz compressor (-J).
Step 4: View the Contents of a Compressed File
If you have a compressed plain text file (like a system log) and you want to read its contents without permanently extracting it to the hard drive, use the xzcat utility. This decompresses the file directly into standard output (your terminal screen):
xzcat system_log.txt.xz | less
Step 5: Extract an XZ Archive
To decompress a standalone .xz file back to its original state, you can use the unxz command (which is simply an alias for xz -d):
unxz database_backup.sql.xz
If you are dealing with a directory bundle (a .tar.xz file), you must use tar to extract (-x) it:
tar -xJf logs_archive.tar.xz
The files will be extracted into your current working directory, fully uncompressed and ready for use.