How can you extract only the target dir and not the complete dir tree?


tar cf /var/www/site.tar /var/www_bak/site


tar xf /var/www/site.tar -C /tmp

This will produce:


How is it possible to avoid the whole dir tree to be created when the file is extracted?

What I want it to extract to:


Why not use -C option when creating:

$ tar cf /var/www/site.tar -C /var/www_bak/ site
  • 1
    TMTOWTDI. That would work too, using the same -C option ;) – MikeyB Nov 11 '11 at 17:27
  • 17
    He wants to strip the path from some leading components, not change the output directory. See below for the correct answer. – aymericbeaumet Jul 28 '15 at 13:50
  • 12
    We can't use it when someone else prepares the archive. – user145545 Jun 16 '18 at 19:42
  • Because ``` _t=prefix-$( date +%Y%m%d ); tar -cjf ".backups/$_t.tar.bz2" --transform="s#^(\./)?#$_t/#x;" -- files...; tar -df ".backups/$_t.tar.bz2" --strip-components=1 ``` – AnrDaemon Sep 3 '18 at 15:36

You want to use the --strip-components=NUMBER option of tar:

       strip NUMBER leading components from file names on extraction

Your command would be:

tar xfz /var/www/site.gz --strip-components=2 -C /tmp
  • 29
    This answer is better because you do not have to think about it before the tar creation. You can use it with an already created tar file. Thanks @MikeyB ! – Fabien Quatravaux Mar 25 '14 at 8:39
  • 7
    I'm pleased to report this works both in GNU tar and BSD tar. – Nathan Osman Jun 20 '16 at 22:07
  • 8
    and because you may not be the tar creator... (or if you're doing it with another tool and that tool does silly things...) – xenoterracide Aug 13 '16 at 4:58
  • 3
    @FabienQuatravaux Well, yes---if you made a mistake and created an archive that includes leading directories that you do not want to see during extraction. But it's clearer to build the archive without the leading undesirable directories in the first place. – Calaf Nov 15 '18 at 12:13
  • 3
    This is the right answer! – geckos Jun 12 '19 at 17:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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