Compression in computing has been around for decades, and new formats of compression come out every so often that are more efficient than others. In this article, I will be showing you how you can compress and decompress files using the bz2 format in Linux on the command line.
What is the bz2 format?
According to their manual file:
bzip2 compresses files using the Burrows-Wheeler block sorting text compression algorithm, and Huffman coding. Compression is generally considerably better than that achieved by more conventional LZ77/LZ78-based compressors, and approaches the performance of the PPM family of statistical compressors.https://linux.die.net/man/1/bzip2
Depending on your Linux operating system, you may need to install a package to use it.
First, check to see if you have the package:
If you get a response such as
/bin/bzip2, etc. then you have it installed already! Otherwise, use one of the following commands to install it:
# on Ubuntu/Debian based operating systems sudo apt install bzip2 # on CentOS based operating systems sudo yum install bzip2 # on Arch Linux and Arch based systems pacman -Sy bzip2
Using bzip2 to compress file(s)
You can use the following command to compress a single file:
# -z tells bzip2 to compress. bzip2 -z yourfile
WARNING: bzip2 will delete input files (those that you have compressed) once it has finished. To have it keep the files, append
-k to the command, like so:
# -z tells bzip2 to compress and -k tells bzip2 to keep the input files after it has finished bzip2 -kz yourfile
Using bzip2 to compress folders/directories
To use bzip2 on a folder or directory, you will need to make a .tar archive first, then use bzip2 on the folder.
Making a tar archive is easy! Use the following command on the folder you want to make a tar file of:
# -c tells tar to create a new archive, -f tells it to store the archive to the specified file tar -c -f myarchive.tar ./folder1/ ./folder2/ ./folder3/ ./myfile.txt
You now have a .tar version of your folder(s) and file(s).
Now we can use the bzip2 command to compress the file, as in the above instructions:
# -z tells bzip2 to compress. (if you want to keep the original .tar file, use -kz instead of just -z) bzip2 -z myarchive.tar
Now, we have a new file:
archive.tar.bz2, which, depending on your use case, will save you a lot of disk space for archiving purposes.
Using bzip2 to decompress files
Once you have a .bz2, .bz, .tbz2, or .tbz file, you can decompress it with the following command:
# -d tells bzip2 to decompress, use -dk instead to keep the original bzip2 file, otherwise it will be deleted. bzip2 -d mycompressedfile.bz2
Using tar to decompress .tar.bz2 files
# -x tells tar to extract, -j tells tar to use bzip2, -f tells tar which file to decompress tar -xjf myarchive.tar.bz2
While commands like these are not always easy to remember, you can always use the
man command, then press
/ and type what you want to search for in the man page.