tar (Linux archiving utility)

This command is mostly used to pack or unpack compressed archives in the format .tar.gz or .tar.bz2, often referred to as “tarballs”. To view the contents of a TAR archive, call tar like so:

tar tf archive.tar.gz

This will list the contents of archive.tar.gz. Note that tar uses option letters without a dash, a legacy from older Unix versions of the command. Somewhat counterintuitively, the option t means “list” and the option f tells tar to expect a file name on the command line.

You can create a new TAR archive like so:

tar cvzf new.tar.gz file1 dir1 ...

This will tell tar to create a new archive called new.tar.gz and populate it with file1, dir1 and any other files or directories specified on the command line. The contents of dir1 will be included in the archive because tar works recursively by default. Shell wildcards are often used instead of file names, for example:

tar cvzf new.tar.gz *.jpg

This will create an archive of all files ending in .jpg. There are three new option letters to be learned from the above examples:

  • c is for “create”. The option instructs tar to create an archive.
  • v is for “verbose”. The option makes tar output a list of files and directories added to the archive.
  • z is for “zip”. The option tells tar to compress the archive using gzip.

Files compressed using the z option end in .gz by convention. You can produce “pure” .tar archives by leaving out the z option, but that would be pointless because compressing files using gzip is fast and saves disk space.

tar offers an alternative compression method called bzip2, which is more time-consuming than gzip but achieves higher compression rates. You can select this method by specifying the option j instead of z, like this:

tar cvjf new.tar.bz2 file1 ...

Archives compressed with bzip2 conventionally end in .bz2.

Finally, the following example shows how to unpack a tarball:

tar xvzf archive.tar.gz

The option letter x is for “extract”. To unpack a .tar.bz2 archive, use the option j instead of z.