How to Use the bzip2 Command to Compress Files in Linux

When you are managing a Linux server, disk space is at a premium. If you have massive log files, database dumps, or old text documents that you don’t need to read immediately but cannot safely delete, the best solution is to compress them.

While gzip is the most famous compression tool in Linux, the bzip2 command is highly regarded for producing significantly smaller file sizes. It uses the Burrows-Wheeler block sorting text compression algorithm, which takes slightly longer to run than gzip, but saves much more hard drive space.

How to Compress a File with bzip2

Compressing a file is incredibly simple. Open your terminal and use the following syntax:

bzip2 filename.txt

For example, if you have a massive 5GB database export named backup.sql, you would type:

bzip2 backup.sql

Important Note: By default, the bzip2 command is destructive. It will compress the data into a new file called backup.sql.bz2, and then it will automatically delete the original, uncompressed backup.sql file.

How to Keep the Original File

If you want to compress a file but you still need to keep the original, uncompressed version on your hard drive, you must use the -k (keep) flag.

bzip2 -k backup.sql

This will leave backup.sql alone, and safely create a new, compressed backup.sql.bz2 file next to it.

How to Extract a .bz2 File

When you eventually need to read the compressed data, you must decompress (extract) the archive. To do this, you use the companion command, bunzip2.

bunzip2 backup.sql.bz2

Just like the compression command, bunzip2 will extract the original file and automatically delete the .bz2 archive. If you want to extract the file but keep the compressed archive as well, use the -k flag again:

bunzip2 -k backup.sql.bz2

How to Compress Multiple Files

It is important to understand that bzip2 is a file compressor, not an archiver. It cannot bundle a whole directory of files into a single package (like a Windows .zip file).

If you type bzip2 file1.txt file2.txt file3.txt, Linux will not merge them. Instead, it will individually compress each file, leaving you with file1.txt.bz2, file2.txt.bz2, and file3.txt.bz2.

To compress a directory into a single file using the bzip2 algorithm, you must combine it with the tar command by using the -j flag (e.g., tar -cjf archive.tar.bz2 /my_folder/).

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.

Receive our best articles and tips delivered straight to your inbox.