bzip2: Compressing files using bzip2
The command bzip2 can be used to compress files and reduce their size. The command accepts one or more files as input on the command line and compresses each of them separately.
Each compressed file is stored with the same name along with “.bz2” added as the extension. By default the original file is replaced unless explicitly specified to retain the original file.
The command works of files only, thus if we want to compress a folder using bzip2 we need to convert it to a file using the tar command and then compress it using bzip2.
Let us say we have a folder called temp. The size of the folder can be found using the command du.
$ du -h temp 52M temp
We can convert the folder into a “.tar” file using the command tar
Note: Using tar command is given in the post : Using tar to create an archive
$ tar cf temp $ du -h temp.tar 52M temp
We can see that the “tar” command only archives but does not compress the file.Now we can use the bzip2 command on the tar file to compress it.
$ bzip2 temp.tar $ ls temp.tar.bz2
We can see that the original file “temp.tar” has been replaced by the compressed file.
$ du -h temp.tar.bz2 37M temp
The size of the compressed file is much smaller than the original file, thus clear that bzip2 compresses the file.s
To retain the original files while compressing using bzip2 we need to use the option “-k”
$ bzip2 -k temp.tar $ ls temp.tar temp.tar.bz2
The files compressed using bzip2 can be decompressed using bzip2 with option “-d” or with the command bunzip2. By default bzip2 creates the decompress file with the name of the original file with “.bz2” removed i.e temp.tar.bz2 will become temp.tar.
$ bzip2 -d temp.tar.bz2 bzip2: Output file temp.tar already exists.
If temp.tar already exists in the folder bzip2 throws an error and stops with out overwriting the file. We can force it to overwrite the existing file by using the option “-f”.
$ bzip2 -d -f temp.tar.bz2 $ ls temp.tar
Again the original “.bz2” file is replaced with the decompressed file, and the option “-k” can be used to retain the compressed file.