Oracle DBA FAQ‎ > ‎

How to tar and untar files in UNIX?

posted Sep 11, 2010, 6:34 AM by Sachchida Ojha

To pack and compress (one step at a time):
tar -cf packed_files.tar file_to_pack1 file_to_pack2 ...

gzip packed_files.tar

 To pack and compress all at once:
tar -cf - file_to_pack1 file_to_pack2 ... | gzip -c > packed_files.tar.gz

 To create a tar from a directory and its subdirectories:
tar -cvf packed_files.tar dir_to_pack

To unpack tar files, use the following commands:
for an uncompressed tar file:
tar -xvf file_to_unpack.tar

To decompress and unpack one step at a time:
gunzip packed_files.tar.gz
tar -xf packed_files.tar

 To decompress and unpack all at once:
gunzip -c packed_files.tar.gz | tar -xf -

 To list the contents of a tar file, use the following command:
tar -tvf file_to_list.tar
To use bzip2 instead of gzip, simply replace the commands above with bzip2 where gzip is used and bunzip2 where gunzip is used.

Compression options
BSD and GNU tar have a compression flag feature making it easier to archive and compress gzipped, bzipped or compressed tarballs in one go. The following commands can be used to take advantage of this:

To pack and compress:
using gzip:
tar -czf packed_files.tgz file_to_pack1 file_to_pack2 ...

 using bzip2:
tar -cjf packed_files.tbz2 file_to_pack1 file_to_pack2 ...

 using compress:
tar -cZf packed_files.tar.Z file_to_pack1 file_to_pack2 ...

 using some other arbitrary compression utility that works as a filter:
tar --use-compress-program=name_of_program -cf packed_files.tar.XXX file_to_pack1 file_to_pack2 ...

 To uncompress and unpack:
a gzip compressed tar file:
tar -xzf file_to_unpack.tar.gz
a bzip2 compressed tar file:
tar -xjf file_to_unpack.tar.bz2
a compress compressed tar file:
tar -xZf file_to_unpack.tar.Z
an arbitrary-compression-utility-compressed tar file:
tar --use-compress-program=name_of_program -xf file_to_unpack.tar.XXX
Some versions of tar use the -y switch to invoke bzip2 rather than -j.

Historical tricks
The following syntax (not related to archiving) was used almost universally before the -d, -R, -p and -a options were added to the cp command.

To copy directories precisely:
tar -cf - one_directory | (cd another_directory && tar -xpf - )