Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am new to the world of Linux and seem to have run into a stumbling block. I know I can extract a specifc archive using the command tar xvfz archivename.tar.gz sampledir/ however how can I extract sampledir/ to testdir/ rather than the path that the archive is in e.g.currently the archive is in the path /tmp/archivename.tar.gz and I would like to extract sampledir to testdir which is in the path /tmp/testdir.

share|improve this question
up vote 17 down vote accepted

What you're looking for is the -C option:

$ man tar

-C, --directory DIR
       change to directory DIR

Usage, per your example:

$ tar xvzf archivename.tar.gz -C /tmp/testdir/ sampledir/

Also, you may be interested to know that modern versions of tar don't require the z flag to decompress gzipped files; they'll notice it's a .gz and Do The Right Thing automatically.

share|improve this answer
Thanks. Funnily I did try that before posting the question and it failed. Maybe I missed an option. I'll try it again. – PeanutsMonkey Jul 13 '11 at 0:57
Brilliance. I always forget about this for large archives. – zmonteca Jun 11 '13 at 6:07

You don't need to play crazy games with untarring everything. Tar fully supports only extracting a subset of the files in an archive, as shown in the following (trivial) example:

/tmp $ mkdir tarsrc
/tmp $ cd tarsrc
/tmp/tarsrc $ mkdir a b
/tmp/tarsrc $ touch a/aaa b/bbb
/tmp/tarsrc $ tar cf ../tartest.tar .
/tmp/tarsrc $ cd ..
/tmp $ mkdir tardest
/tmp $ cd tardest
/tmp/tardest $ tar xf ../tartest.tar ./a    
/tmp/tardest $ ls -R


The trick is that the pathspec must match the contents of the tarfile exactly. So when you do a tar tf, if the path starts with ./, you've got to put that in, and if it doesn't have it, you have to leave it out. Also, if you want to extract a sub-sub-sub-sub-sub-sub-sub-path, it'll end up N levels deep in the filesystem when you're done.

share|improve this answer
Thanks womble. Maybe it isn't the right example to use but I am comparing tar to Winzip, WinRAR, etc and possibly tar is the incorrect command to use however seeing that I have seen example of tar unarchiving gzip and bzip files, I was hoping I could apply similar process e.g. select the file you like to unarchive (tar does this) and select the path you would like to extract to (tar does not do this unless I am in the specific directory). – PeanutsMonkey Jul 12 '11 at 23:45
You want the -C option to tar, then. – womble Jul 13 '11 at 0:01

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.