5.5. tar: Tape ARchiver

Although we have already seen a use for tar in the chapter "Building and installing free software", we haven't explained how it works. This is what this section is here for. As for find, tar is a long standing Unix utility, and as such its syntax is a bit special. The syntax is:

tar [options] [files...]

Now, here is a list of options. Note that all of them have an equivalent long option, but you will have to refer to the manual page for this as they won't be listed here. And of course, not all options will be listed either :-)

Note

the initial dash (-) of short options is now deprecated with tar, except after a long option.

There are many, many, many other options, so you may want to refer to the tar(1) manual page for a whole list. See, for example, the d option. Now, on for a little practice. Say you want to create an archive of all images in /shared/images, compressed with bzip2, named images.tar.bz2 and located in your home directory. You will then type:

 #
 # Note: you must be in the directory from which 
 #   you want to archive files!
 #
$ cd /shared
$ tar cjf ~/images.tar.bz2 images/

As you can see, we have used three options here: c told tar that we wanted to create an archive, j told it that we wanted it compressed with bzip2, and f ~/images.tar.bz2 told it that the archive was to be created in our home directory, with name images.tar.bz2. We may want to check if the archive is valid now. We can just check this out by listing its files:

 #
 # Get back to our home directory
 #
$ cd
$ tar tjvf images.tar.bz2

Here, we told tar to list (t) files from archive images.tar.bz2 (f images.tar.bz2), warned that this archive was compressed with bzip2 (j), and that we wanted a long listing (v). Now, say you have erased the images directory. Fortunately, your archive is intact, and you now want to extract it back to its original place, in /shared. But as you don't want to break your find command for new images, you need to preserve all file attributes:

 #
 # cd to the directory where you want to extract
 #
$ cd /shared
$ tar jxpf ~/images.tar.bz2

And here you are!

Now, let's say you want to extract the directory images/cars from the archive, and nothing else. Then you can type this:

$ tar jxf ~/images.tar.bz2 images/cars

In case you would worry about this, don't. If you try to back up special files, tar will take them as what they are, special files, and will not dump their contents. So yes, you can safely put /dev/mem in an archive :-) Oh, and it also deals correctly with links, so do not worry for this either. For symbolic links, also look at the h option in the manpage.


Tux on Star from MandrakeSoft Linux is a registered trademark of Linus Torvalds. All other trademarks and copyrights are the property of their respective owners.
Unless otherwise stated, all the content of these pages and all images are Copyright MandrakeSoft S.A. and MandrakeSoft Inc. 2001.
http://www.mandrakelinux.com/