Torbjorn Zetterlund

Mon 26 2012

How to use the linux tar command

by bernt & torsten

If you looking at creating a “zip” archive file under Linux, the command to use is tar. To create an archive using tar, use a command like this, which bundles all the files in the current directory that end with .c into the sourcefiles.tar file:

tar cvf sourcefiles.tar *.c

Achieving a directory, that creates a tar file named tbearfill.tar containing all the files from the tbearfill directory (and any of its subdirectories):

tar cvf tbearfill.tar tbearfill

In these examples, the c, v, and f flags mean to create a new archive, be verbose (list files being archived), and write the archive to a file. You can also create tar files on tape drives or floppy disks, like this:

tar cvfM /dev/fd0 tbearfill Archive the files in the tbearfill directory to floppy disk(s).

tar cvf /dev/rmt0 tbearfill Archive the files in the tbearfill directory to the tape drive.

The /dev/fd0 entry is Linux-ese for “floppy drive zero” (your A: drive under DOS), and /dev/rmt0 means “removable media tape zero,” or your primary tape drive. The M flag means to use multiple floppy disks–when one disk is full, tar prompts you to insert another.

To automatically compress the tar file as it is being created, add the z flag, like this:

tar cvzf sourcefiles.tar.gz *.doc

In this example, I added the .gz suffix to the archive file name, because the z flag tells tar to use the same compression as the gzip command.

To list the contents of a tar file, use the t (type) flag in a command, like this:

tar tvf sourcefiles.tar List all files in sourcefiles.tar.

To extract the contents of a tar file, use the x (extract) flag in a command, like this:

tar xvf tbearfill.tar Extract files from tbearfill.tar.

This will copy all the files from the tbearfill.tar file into the current directory. When a tar file is created, it can bundle up all the files in a directory, as well as any subdirectories and the files in them. So when you’re extracting a tar file, keep in mind that you might end up with some new subdirectories in the current directory.

We’ve used several different flags in the sample tar commands so far. Here’s a list of the most common flags:

c – Create a new archive.
t  – List the contents of an archive.
x  – Extract the contents of an archive.
f  – The archive filename is given on the command line (required whenever the tar output is going to a file)
M  – The archive can span multiple floppies.
v  – Print verbose output (list filenames as they are processed).
u  – Add files to the archive if they are newer than the copy in the tar file.
z  – Compress or decompress files automatically.