How do I use the tar command?
Author: Deron Eriksson
Description: This Linux tutorial demonstrates some of the basic features of the tar command.
Tutorial created using: CentOS release 4.6


The tar (tape archive) command is a useful command that can be used to group a set of files into a single archive file and also to ungroup an archive file into its constituent files. The GNU tar command includes the ability to compress the tar file using gzip compression, which produces a .tar.gz file.

First, let's look at creating an archive file. This is done with the "c" (create) option. The "v" (verbose) option let's us know what files are being archived. The "f" (file) option specifies that we'll use an archive file. The "z" (gzip) option specifies to filter the archive file through gzip, which means that the archive will be compressed.

I have a directory called "testing" with two files in it, "test" and "test2". I'll run the following commands:

tar cvf one.tar testing
tar cvzf two.tar.gz testing

The first command takes the "testing" directory and creates a tar file called "one.tar". This file is uncompressed. The second command takes the "testing" directory and creates a gzip-compressed tar file (.tar.gz) called "two.tar.gz".

Here, we can see the execution of these commands and the display of the resulting files. Notice the size of the files. The "one.tar" file is 10240 bytes, and the compressed "two.tar.gz" file is 199 bytes. They both contain the same files.

archive creation with the tar command

The tar command can be used to display the contents of .tar and .tar.gz files. We can do this with the "t" (list) option, which lists the contents of the specified archive file.

Here are two tar commands run on the "one.tar" and "two.tar.gz" files.

tar tvf one.tar
tar tvzf two.tar.gz

The first command verbosely lists the contents of the one.tar file. The second command verbosely lists the contents of the two.tar.gz file. Notice that the second command uses the "z" option to read the contents of the gzipped two.tar.gz file.

listing the contents of the .tar and .tar.gz archives

The tar command can be used to extract the contents of .tar and .tar.gz files. This can be done with the "x" (extract) option. Here are extraction commands run on the "one.tar" and "two.tar.gz" files. Notice that the .tar.gz extraction uses the "z" option.

tar xvf one.tar
tar xvzf two.tar.gz

Here we can see the executions of the above extraction commands and their results.

archive extraction with the tar command

The tar command has LOTS of options. For option details, you can consult "tar --help" and "man tar".