How to Use the bunzip2 Command to Extract Files in Linux

When you download source code, software packages, or massive database backups in Linux, they are frequently compressed using the bzip2 algorithm to save bandwidth. These files always end with the .bz2 extension. Before you can compile the code or import the database, you must extract the original text from the archive and save it back to your hard drive. To accomplish this safely and quickly, you should use the bunzip2 command.

How to Extract a bzip2 File

The bunzip2 command is the standard decompression tool for the bzip2 format. Using it is incredibly simple.

bunzip2 database_backup.sql.bz2

When you run this command, Linux will instantly begin decompressing the file. Once the process is complete, the original .bz2 archive will be automatically deleted, and it will be replaced in the same directory by the fully extracted, uncompressed file (e.g., database_backup.sql). This default behavior is designed to prevent you from accidentally wasting disk space by keeping two identical copies of massive files.

How to Extract a File but Keep the Original Archive

If you downloaded a large software archive from the internet and want to extract it, but you also want to keep the original .bz2 file as a safe backup in case you mess up the installation, you must use the -k (keep) flag.

bunzip2 -k database_backup.sql.bz2

With the -k flag enabled, Linux will extract the uncompressed data into a new file, but it will leave the original compressed archive completely untouched. You will now have both files sitting side-by-side in your directory.

How to Extract to a Different Directory

By default, bunzip2 extracts the file into the exact same folder where the archive is currently located. If you have a compressed file in your Downloads folder but you want to extract the contents directly into your /var/www/ web server directory, you can use the -c (standard output) flag combined with a bash redirect.

bunzip2 -c ~/Downloads/website_files.bz2 > /var/www/website_files.html

This command tells bunzip2 to push the uncompressed data into the terminal stream instead of writing a file, and the > symbol immediately catches that stream and saves it to the new path you specified.

Get the best tech tips delivered straight to your inbox.

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