How to Compress Files Using bzip2 Command in Linux

How to Compress Files Using bzip2 in Linux

Hey there! 👋 Welcome to this Linux tutorial, brought to you by ProgramGuru.org. Today, we're going to learn how to compress files using the bzip2 command — a powerful and space-efficient compression tool available in most Linux systems.

If you’ve ever wanted to save disk space, or make your file transfers faster, bzip2 is a fantastic tool to have in your Linux toolbox. Let’s walk through it step by step.

What is bzip2?

bzip2 is a command-line utility that compresses single files using the Burrows–Wheeler algorithm. It usually provides better compression ratios than gzip.

Step 1: Check if bzip2 is installed

On most modern Linux distros, bzip2 comes pre-installed. But you can verify it with this command:

bzip2 --version

If it's not installed, you can add it using your package manager:

sudo apt install bzip2      # Debian/Ubuntu
sudo yum install bzip2      # RHEL/CentOS
sudo dnf install bzip2      # Fedora

Step 2: Create a sample file

Let’s create a test file to practice with:

echo "This is a test file for compression." > testfile.txt

Step 3: Compress the file

Now let’s compress it using bzip2:

bzip2 testfile.txt

This command will replace the original file with a compressed version:

testfile.txt.bz2

Notice that the original testfile.txt is gone — it’s now inside the compressed file testfile.txt.bz2.

Want to Keep the Original File?

Use the -k (keep) option:

bzip2 -k testfile.txt
testfile.txt
testfile.txt.bz2

Step 4: View the compressed file size

ls -lh testfile.txt.bz2

Step 5: Decompress the file

To unzip it back to the original form, use bunzip2:

bunzip2 testfile.txt.bz2

Or use the -d flag with bzip2:

bzip2 -d testfile.txt.bz2

Bonus Tip: Compress Multiple Files?

bzip2 only works on single files. If you want to compress a whole folder or multiple files, you should first archive them using tar:

tar -cvjf archive.tar.bz2 foldername/

This command:

  • -c: creates an archive
  • -v: shows progress
  • -j: compresses using bzip2
  • -f: specifies the filename

Recap

  • bzip2 filename → compresses the file
  • bunzip2 filename.bz2 → decompresses it
  • -k option → keeps original file
  • tar -cvjf → compresses directories

And that’s it! 🎉 You now know how to compress and decompress files using bzip2. Keep practicing and try it on your own files. If you found this helpful, check out more Linux tutorials at ProgramGuru.org!