Some Linux tar command examples

The Linux tar command is used to created and extract archives. An archive is one file that contains one or (usually) many other files. The name "tar" itself comes from the phrase "tape archive", but that's just an old name. I mostly just create archives and then send them over the wire these days.

Creating Unix/Linux tar archives

To create an archive of all files in your current directory, and all subdirectories, use this tar command:

tar cf my_files.tar *

This command creates a new file named my_files.tar that contains all the files and directories from your current directory (specified by the * filename metacharacter). It doesn't remove your existing files; it just creates an archive that also contains your files.

In this tar command example, the c option means "create" and the f option lets you specify the filename for the archive. And no, it's not a typo: you don't need the hyphen before the options. You can use them if you prefer, but I never use them.

I almost always use the next command instead of the previous command to create a tar archive. The only difference is that I've added the v option to provide verbose output, which gives you output, listing all the files that are going into the archive. Here's that command:

tar cvf my_files.tar *

When I also want to compress the archive with gzip I use this command instead, adding the v argument to indicate that I want to compress the archive with gzip:

tar czvf my_files.tgz *

It's standard to use the .tgz extension when creating a tar archive like this, but you can call it .foo if you want, there's nothing forcing you to call it one thing or another.

That command creates the tar archive and simultaneously compresses it with gzip, similar to this two-step operation:

tar cvf my_files.tar *
gzip my_files.tar

If you do this two-step operation you'll end up with a file named my_files.tar.gz instead of my_files.tgz.

Listing files in a tar archive

To list files in an archive use the t option, like this:

tar tvf my_files.tar

Just add the z option if you used it when creating the archive, like this:

tar tzvf my_files.tgz

Extracting tar archives

To extract all the files from an archive use the x option:

tar xf my_files.tar

As usual, add the v option to get more verbose output:

tar xvf my_files.tar

and add the z option if your archive is already compressed:

tar xzvf my_files.tgz

If you only want to extract one file named "important_file.txt" from your compressed archive this command will do the trick:

tar xzvf my_files.tgz important_file.txt

Other Unix/Linux tar command options

There are a ton of other tar options, but on a daily basis, these are the options I use.

Related tar command posts