Quick take: The xz command compresses files to a smaller size than gzip, at the cost of speed. Use xz file to compress (to .xz), unxz or xz -d to decompress, and -k to keep the original.

Introduction

The xz command offers high compression ratios using the LZMA algorithm — notably smaller output than gzip, which makes it popular for distributing large files, kernels, and software archives. The trade-off is speed: xz compresses more slowly but decompresses quickly.

Syntax

The basic syntax of the xz command is:

xz [OPTIONS] FILE

Common Options and Parameters

The most useful options and parameters for the xz command:

OptionDescription
-dDecompress (same as unxz).
-kKeep the original file.
-0 … -9Compression level (9 is smallest).
-eExtreme mode for slightly better compression.
-T NUse N threads (-T 0 = all cores).
-lList information about a .xz file.
-cWrite to stdout.

Practical Examples

Real xz commands you can run today:

# Compress a file (replaces it with .xz)
xz bigfile.img
# Compress but keep the original
xz -k bigfile.img
# Maximum compression with all cores
xz -9 -T0 bigfile.img
# Decompress
unxz bigfile.img.xz
# Create a tar.xz archive
tar -cJf archive.tar.xz folder/
# Read a .xz file without extracting
xzcat bigfile.img.xz | less

Tips and Best Practices

  • Use -T0 to compress with all CPU cores — xz is slow, and threading helps significantly on large files.
  • Combine with tar using the -J flag: tar -cJf archive.tar.xz folder/.
  • Choose xz when output size matters most (distribution, backups) and gzip when speed matters more.

Final Thoughts

xz delivers the best compression ratio of the common Linux tools, ideal when smaller files matter more than compression time — software distribution, kernels, and archives. Remember -k to keep the original, -T0 to use all cores, and the -J tar flag for .tar.xz. For everyday speed, gzip remains the faster choice.

FAQ: xz Command in Linux

How do I compress a file with xz?+

Run xz filename, which compresses it to filename.xz and removes the original. Add -k to keep the original, and -9 -T0 for maximum compression using all cores.

How do I decompress an .xz file?+

Use unxz file.xz or xz -d file.xz. To read it without extracting, use xzcat file.xz.

What is the difference between xz and gzip?+

xz compresses significantly smaller using LZMA but is slower to compress. gzip is faster with larger output. Use xz when file size matters most and gzip when speed matters more.

How do I create a tar.xz archive?+

Use the -J flag with tar: tar -cJf archive.tar.xz folder/. Extract it with tar -xJf archive.tar.xz.

How do I speed up xz compression?+

Use multiple threads with -T, for example xz -T0 to use all CPU cores. This makes a big difference on large files since xz is otherwise slow.

Need help with Linux servers or infrastructure?

Work directly with Muhammad Irfan Aslam for Linux, Ubuntu, Docker, DevOps, cloud, CI/CD, or infrastructure support.

Hire Me for Support