0
0
Linux CLIscripting~5 mins

bzip2 and xz compression in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes files are too large to store or send easily. bzip2 and xz help by making files smaller using compression. This saves space and speeds up transfers.
When you want to reduce the size of a log file before archiving it.
When you need to send a large text file over email and want it smaller.
When you want to save disk space by compressing old documents.
When you want to compress a backup folder into a single smaller file.
When you want to decompress a downloaded file compressed with bzip2 or xz.
Commands
This command compresses the file example.txt using bzip2. It replaces the original file with a compressed file named example.txt.bz2.
Terminal
bzip2 example.txt
Expected OutputExpected
No output (command runs silently)
This command lists the compressed file to confirm it was created and to see its size.
Terminal
ls -l example.txt.bz2
Expected OutputExpected
-rw-r--r-- 1 user user 1234 Apr 27 12:00 example.txt.bz2
-l - Shows detailed file information including size
This command decompresses the bzip2 file back to the original example.txt file.
Terminal
bunzip2 example.txt.bz2
Expected OutputExpected
No output (command runs silently)
This command compresses example.txt using xz compression. It replaces the original file with example.txt.xz.
Terminal
xz example.txt
Expected OutputExpected
No output (command runs silently)
This command decompresses the xz compressed file back to example.txt.
Terminal
unxz example.txt.xz
Expected OutputExpected
No output (command runs silently)
Key Concept

If you remember nothing else from this pattern, remember: bzip2 and xz compress files by replacing the original with a smaller compressed file, and bunzip2 or unxz restore them.

Common Mistakes
Trying to compress a file without write permission.
The command fails because it cannot replace the original file with the compressed version.
Make sure you have write permission on the file or compress a copy instead.
Using bunzip2 or unxz on a file that is not compressed with the matching tool.
The decompression fails because the file format does not match the tool.
Use bunzip2 only on .bz2 files and unxz only on .xz files.
Expecting the original file to remain after compression.
bzip2 and xz delete the original file by default after compression.
Use the -k flag to keep the original file if needed.
Summary
Use bzip2 or xz to compress files and reduce their size.
bunzip2 and unxz decompress files compressed by bzip2 and xz respectively.
By default, compression replaces the original file unless you use the -k flag.