Compressing and Archiving

Quick Reference

tar.gz     tar xzvf x.tar.gz
bz2        bzip2 -cd file.tar.bz2 | tar xvf -
Z          uncompress file.Z
tar.Z      zcat file.Z | tar xvf -

tar command

The tar command is used to collate collections of files into one larger file.

Creating archives

Suppose we have directory xdir containing many files, we use the following command to archive them into one file.

tar -cvf x.tar xdir


This command would archive the directory xdir and its contents into a file called x.tar. The extension '.tar' is used by convention to indicate tar files.

To create an archive and apply gzip to compress the archive,

tar -czvf x.tar.gz xdir

The only difference from last example is the -z option. By convention, we add '.tar.gz' for tar and gzip compressed files.

Extracting archives

To extract an archive, we use

tar -xvf x.tar

It would be extracted to the same directory by default.

To extract a zipped archive, we use

tar -xzvf x.tar.gz

To extract a zipped archive, we use

tar -xzvf x.tar.gz -C another_dir

tar would extract all files to a directory called another_dir

Common command options
c is for create
v is for verbose
f is to store in a file else it will go to stdin/stdout
x is for extract
z is for gzip, ungzip to unzip
j is for bzip2
p is to preserve permissions
C is to direct output to a user-specified location

gzip, gunzip, zcat

New unix users often get confused with gzip, gunzip, and zcat.

gzip
gzip compresses a single file. A tar archive is a single file, so it is common to use tar files in conjuction with gzip

gzip -c xdir.tar > xdir.tar.gz

uncompress
gzip -d xdir.tar.gz

or
gunzip xdir.tar.gz

uncompressing a .bz2 file

bzip2 -cd file.tar.bz2 | tar xvf -

or
bzcat file.tar.bz2 | tar xvf -