166

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

compress

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

extract

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

This will produce:

/tmp/var/www/site

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:

/tmp/site
NReilingh
  • 484
  • 3
  • 9
  • 24
clarkk
  • 2,035
  • 8
  • 24
  • 36

2 Answers2

426

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

 --strip-components=NUMBER
       strip NUMBER leading components from file names on extraction

Your command would be:

tar xfz /var/www/site.gz --strip-components=2 -C /tmp
MikeyB
  • 39,291
  • 10
  • 105
  • 189
  • 32
    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 08:39
  • 8
    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 04:58
  • you might still be missing `--strip-components` flag if you're using busybox-embedded implementation of `tar`, though. – sylvainulg May 31 '18 at 12:45
  • 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
  • 5
    This is the right answer! – geckos Jun 12 '19 at 17:57
  • @NathanOsman this *may* work with some recent versions of GNU tar or its other flavors, but that option is not available in legacy GNU versions that are still out there. – Anton Samsonov Sep 06 '21 at 05:37
  • If you want to remove *all* leading paths then use `--transform='s/^.*\///'` instead of strip-components. – CR. Sep 14 '22 at 21:07
  • At least with the FreeBSD 12.3 version of `tar`, `--strip-components=2` would only strip the leading slash and the first dir. To remove all of it, you'll need `--strip-components=3`. – emk2203 Dec 11 '22 at 22:32
  • This also works very well when you change the directory structure in a project, or need to often download design files into a develop repository (e.g. with git archive). – Frank Forte Mar 29 '23 at 20:35
53

Why not use -C option when creating:

$ tar cf /var/www/site.tar -C /var/www_bak/ site
quanta
  • 51,413
  • 19
  • 159
  • 217