FOSSwire Reference - Using tar to create, extract and manipulate archives

  • May 21, 2007
  • Avatar for peter
    Peter
    Upfold

Quick headnote - welcome to a new breed of FOSSwire post, the Reference post. In a Reference post, we'll try to put as much useful information as possible that you might want to quickly come back and find later!

If you've ever worked with a Unix system, you've probably used tar. Put simply, tar is a way to archive a folder, or multiple files into one file (and optionally add compression). It comes in really handy for pretty much anything, from backups, to moving files between places to using it to store lots of files for a download.

We're using GNU tar here, which is pretty much standard everywhere. If you're using a different flavour of tar, not everything here might work.

So let's get straight to it!

Creating an archive


Run tar with the c switch to create an archive. You'll probably want to also use the f switch to send tar's output to a file:
$ tar cf outputfile.tar inputs

To add compression, use the z switch for gzip, and the j switch for bzip2:
$ tar cjf outputfile.tar.bz2 inputs

Finally, you can also use the v switch (verbose) to watch progress.

Extracting an archive


Extracting is basically the same, but you use the x option to extract:
$ tar xf inputfile.tar

That will extract said archive to the current directory. For a compressed archive, you'll again need to add the z for a .tar.gz, or j for .tar.bz2.
$ tar xjf inputfile.tar.bz2

Again, to see progress you may want to add the v option for verbose logging.

Listing contents of an archive


The t switch is helpful if you want to peek into an archive without actually extracting it. Unless you're piping output in and out, you'll need to use the f switch again to determine the archive file.
$ tar tvf myarchive.tar

You will get an ls -l style listing of the contents. You may wish to pipe the output to less for a large archive for readability.

Again, for compressed tar archives, add z or j.

Wrapping up


There's plenty more that tar can do, so I've just touched on the most common uses of tar. Feel free to fire your power tar user tips in the comments!

Avatar for peter Peter Upfold

Home » Articles »