bzip2 Command

The bzip2 command is a data compressor that uses the Burrows-Wheeler block-sorting text compression algorithm, and Huffman coding. It generally achieves a higher compression ratio than the more common gzip.

Syntax

bzip2 [ options ] [ filenames ... ]

Description

bzip2 compresses the specified files. Each file is replaced by its compressed version, with the name original_name.bz2. If no filenames are specified, bzip2 compresses from standard input to standard output.

Common uses include:

  • Compressing single files
  • Decompressing .bz2 files
  • Compressing data from standard input

Common Options

Option Description
-d, --decompress Force decompression
-z, --compress Force compression
-k, --keep Keep (don't delete) input files during compression or decompression
-f, --force Force overwrite of output files
-v, --verbose Be verbose during operation
-c, --stdout Compress or decompress to standard output
-s, --small Reduce memory usage, at cost of speed

Examples

Compress a file

bzip2 myfile.txt
# Result: myfile.txt.bz2 (original file is deleted)

Compresses myfile.txt and replaces it with myfile.txt.bz2.

Decompress a file

bzip2 -d myfile.txt.bz2
# Result: myfile.txt (original .bz2 file is deleted)

Decompresses myfile.txt.bz2 and restores myfile.txt.

Compress and keep original file

bzip2 -k anotherfile.log
# Result: anotherfile.log and anotherfile.log.bz2 both exist

Compresses anotherfile.log but keeps the original file.

Decompress to standard output

bzip2 -dc compressed.bz2 > decompressed.txt

Decompresses compressed.bz2 and redirects the output to decompressed.txt.

Compress a directory (using tar and pipe)

tar -cf - mydirectory/ | bzip2 -c > mydirectory.tar.bz2

Compresses an entire directory by piping tar output to bzip2.

See also