How to compress and decompress (extract) files and folders using bzip2 (bz2)

"bzip2" is a data/file compression program that lacks archiving functionality.

Note: The name of compressed file generated by Bzip is based on the same of the source file (followed by the extension ".bz2).

What about bzip/bzip1?

Apperently, there was a program simply called "bzip", but there was some sort of patent dispute that lead to the creation of bzip2.

Installation

If your computer/server does not have bzip2 pre-installed, you'll need to install it.

apt install bzip2

Compress

By default, bzip2 will not replace/erase an existing file.

Single file

Syntax
bzip2 [file]
  • [file] -- The filename/filepath of the bzip2 file you wish to compress.
Example
bzip2 foo.txt

Multiple files (in a directory)

If you want to compress multiple files, type bzip2 followed by files you want to compress. Each file needs to be seperated blank space. You can enter an arbitrary number of files to be compressed.

Remember: bzip2 does archive files. bzip2 will created a compressed file for each file entered.

Syntax
bzip2 [file1] [file2] [file3]
Example
bzip2 index.html logo.png readme.txt
Result
  • index.html.bz2
  • logo.png.bz2
  • readme.txt.bz2

Overwrite existing files

This applies to commands that cite either single or multiple files.

Syntax
 bzip [file]
  • r -- If bunzip needs to create a file that has the same name as a file in the current/target directory, the -r flag while allow the existing file to be erased/replaced.
  • [file] -- The filename/filepath of the bzip2 file you wish to decompress.
Example
bzip -f report.csv

Decompress

Without overwriting existing files

Syntax
 bunzip2 [file]
  • [file] -- The filename/filepath of the bzip2 file you wish to decompress.
Example
 bunzip2 -f foo.bz2

Overwrite existing files

Syntax
 bunzip2 [file]
  • r -- If bunzip is extracting a file that has the same name as a file in the current/target directory, the -r flag while allow the existing file to be erased/replaced.
  • [file] -- The filename/filepath of the bzip2 file you wish to decompress.
Example
bunzip2 -f database.sql