Pages

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.

Example:
Let us say we have a folder called temp. The size of the folder can be found using the command du.



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



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.



We can see that the original file "temp.tar" has been replaced by the compressed file.



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"



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.

Example



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".



Again the original ".bz2" file is replaced with the decompressed file, and the option "-k" can be used to retain the compressed file.


3 comments:

  1. Shouldn't the title be "bzip2: Compressing files using bzip2"? Instead of "bzip2: Compressing files using bunzip"? (i.e. bunzip is for de-compressing)

    Otherwise nice article!

    ReplyDelete
    Replies
    1. Thank you for the feedback, have updated it.

      Delete
  2. Thanks for this nice article.

    ReplyDelete