79

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

compress

tar cf /var/www/site.tar /var/www_bak/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
28

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
  • 9
    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
  • 3
    We can't use it when someone else prepares the archive. – jww 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
216

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
  • 17
    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
  • 3
    I'm pleased to report this works both in GNU tar and BSD tar. – Nathan Osman Jun 20 '16 at 22:07
  • 2
    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
  • 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
  • @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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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