Overview
When maximum space savings take priority in Linux environments, xz stands out as the premier compression utility. Powered by the LZMA/LZMA2 algorithms, it delivers industry-leading data shrinking rates that surpass traditional gzip and bzip2 tools. This practical walkthrough covers essential workflows: standard file compression and extraction, safety switches for file retention, compression preset optimization, multithreaded performance boosts, and seamless archive bundling.
Installing xz-utils and Mastering Basic Compression (–keep)
Before utilizing the utility on Ubuntu, ensure the required binaries and shared libraries are installed by fetching xz-utils:
apt-get update -qq && apt-get install -y xz-utils

Set up an isolated workspace for hands-on testing and navigate into it:
mkdir -p ~/xz_practice && cd ~/xz_practice

Generate an arbitrary 5MB test payload of pseudo-random text using /dev/urandom:
base64 /dev/urandom | head -c 5000000 > sample1.txt

Duplicate the dataset so we can compare default destructive behavior against non-destructive archiving:
cp sample1.txt sample2.txt

Executing xz in its simplest form compresses the target into a .xz archive. Note that by default, the command aggressively purges the uncompressed original upon completion:
xz sample1.txt
⚙️ [Key Command Flags]
-z, --compress : Force compression mode explicitly (default behavior).-d, --decompress : Trigger decompression mode, equivalent to invoking unxz.-k, --keep : Prevent removal of source files after finishing the process.-f, --force : Overwrite destination targets if they already exist without prompting.-l, --list : Inspect container metadata, uncompressed dimensions, and ratios without decompressing.-v, --verbose : Display real-time progress, compression ratios, processing rates, and elapsed time.-0 to -9 : Adjust algorithm strength presets (higher values minimize footprint at the cost of CPU cycles and memory).-T, --threads : Allocate worker thread counts to unlock parallel processing across CPU cores.

To preserve the raw data alongside the newly produced .xz container, append the -k (--keep) flag:
xz -k sample2.txt

Inspecting the directory contents highlights how standard invocation consumed sample1.txt leaving only sample1.txt.xz, whereas the -k flag retained both sample2.txt and its compressed counterpart:
ls -lh sample*

Decompressing with unxz and Inspecting Archives On the Fly
Return to the practice directory to proceed with decompression exercises:
cd ~/xz_practice

You can query inner stream counts, raw file sizes, compressed volume, compression ratios, and integrity checksum standards (e.g., CRC64) without touching disk I/O using the -l inspection switch:
xz -l sample1.txt.xz

To unpack an archive back to its raw form, employ the dedicated unxz shortcut (or xz -d). Under default settings, this operation unpacks sample1.txt and purges the compressed .xz container:
unxz sample1.txt.xz

When administering production servers, inspecting log streams without writing decompressed artifacts to disk saves substantial storage and IOPS. Create a small payload to illustrate standard stream inspection:
echo 'Linux xz compression test data stream' > stream_test.txt

Package this payload while keeping the source intact:
xz -k stream_test.txt

Use xzcat to stream the decoded contents directly to standard output without persisting unpacked bytes to disk:
xzcat stream_test.txt.xz

A quick directory listing confirms that sample1.txt is fully restored, while both the uncompressed and compressed variants of stream_test remain intact:
ls -lh sample1.txt stream_test.*

Tuning Compression Levels and Accelerating with Multithreading (-T)
Switch back to the working root before exploring tuning knobs:
cd ~/xz_practice

Synthesize a larger 10MB test dataset to observe distinct benchmark trade-offs between speed and efficiency:
base64 /dev/urandom | head -c 10000000 > big_sample.txt

For high-throughput pipelines where CPU conservation outranks file size reductions, invoke level -1:
xz -k -1 big_sample.txt

Rename this intermediate artifact so subsequent tests do not overwrite it:
mv big_sample.txt.xz big_sample_fast.txt.xz

By default, xz operates in single-threaded mode, making preset -9 computationally expensive. By specifying -T0, the utility queries your host CPU topology and engages every available core simultaneously to accelerate extreme compression:
xz -k -9 -T0 big_sample.txt

Label the resulting high-density archive:
mv big_sample.txt.xz big_sample_ultra.txt.xz

Review the generated targets side-by-side to evaluate how the presets affected size and processing trade-offs:
ls -lh big_sample*

Bundling Archives: Integrating tar with xz Compression
Because xz functions exclusively as a single-stream compressor rather than a multi-file archiver, pairing it with tar is standard practice for packaging full directory trees. Ensure you are in the workspace:
cd ~/xz_practice

Construct a mock multi-tier application hierarchy containing source modules and log directories:
mkdir -p my_project/logs my_project/src

Populate the source branch with an entry-point stub:
echo 'package main' > my_project/src/main.go

Seed the logging directory with sample telemetry:
echo 'Application started successfully' > my_project/logs/app.log

Pass the -J option directly to tar to encapsulate the directory structure and stream it directly through the LZMA2 compression engine, producing my_project.tar.xz:
tar -cJf my_project.tar.xz my_project

To audit permissions, ownership metadata, and file hierarchies inside the tarball without touching the local disk, use table-of-contents mode (-tvf):
tar -tvf my_project.tar.xz

Unpack the archive cleanly into a dedicated subfolder using -C alongside the -xJf extraction switches:
mkdir -p extracted_dir && tar -xJf my_project.tar.xz -C extracted_dir

Verify that file sizes, permissions, and internal structures were faithfully restored within the destination tree:
ls -lh my_project.tar.xz extracted_dir/my_project

Equipped with these commands and options, you can effectively leverage xz across Ubuntu servers to drastically curb storage footprints during database backups, cold storage archiving, and bandwidth-constrained network transfers.