(de)compressing files

What is the best compression algorithm

This is a question one can fight many holy wars about - and it of course depends what data (=files) you are looking to compress. See question 5 of the
compression FAQ for more on this topic. Of the compression programs that are most used under UNIX on average you probably will get the best result with bzip2 followed by gzip. However, gzip is still more commonly available.

How do I decompress a file with extension .xxx ?

For a complete list of possible extension and compression programmes see question 2 of the
compression FAQ.
Extension Note compress command decompress command
.bz2   bzip2 bunzip2
.gz GNU zip gzip gunzip
.tgz gzip-ed tar file gtar -zcf <file> gtar -zxf <file>
.Z UNIX compress compress uncompress

Handling compressed tar files

This depends on which tar command you are using. GNU tar is (IMHO) usually better than Solaris tar. The following lists several options to compress and decompress tar files.

To tar something up and compress it at the same time:

Solaris tar
tar -cf - <files> | gzip - > <tarfile>.tgz;
tar -cf - <files> | bzip2 - > <tarfile>.tar.bz2;
GNU tar
gtar -zcf <tarfile>.tgz; <files>
gtar -ycf <tarfile>.tar.bz2; <files>

To decompress and untar a file at the same time:

Solaris tar
gzcat <tarfile>.tgz | tar -xf -
gzip -cd <tarfile>.tgz | tar -xf -
bzcat <tarfile>.tar.bz2 | tar -xf -
bzip2 -cd <tarfile>.tar.bz2 | tar -xf -
GNU tar
gtar -zxf <tarfile>.tgz;
gtar -yxf <tarfile>.tar.bz2;

How to view the content of a compressed file ?

If you just want to look at the content of a compressed file without decompressing it use one of the following commands:
zcat <file>.Z
gzcat <file>.Z
(yes, gzcat and gunzip also work for .Z files)
gzcat <file>.gz
(note: gzcat is equivalent to "gzip -cd")
bzcat <file>.bz2
(note: bzcat is equivalent to "bzip2 -cd")
It is often a good idea to pipe the output into a pager like more or less.

How to test the integrity of a compressed file ?

Sometimes after transfering a file you might want to test if the compressed file is OK. You can do this with one of the following commands:
gzip -t <files>.gz
bzip2 -t <files>.bz2

04. May. 2000
Robert Greimel