161

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

2 Answers 2

53

Why not use -C option when creating:

$ tar cf /var/www/site.tar -C /var/www_bak/ site
4
  • 1
    TMTOWTDI. That would work too, using the same -C option ;)
    – MikeyB
    Nov 11, 2011 at 17:27
  • 20
    He wants to strip the path from some leading components, not change the output directory. See below for the correct answer. Jul 28, 2015 at 13:50
  • 14
    We can't use it when someone else prepares the archive.
    – user145545
    Jun 16, 2018 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, 2018 at 15:36
417

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
10
  • 31
    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 ! Mar 25, 2014 at 8:39
  • 8
    I'm pleased to report this works both in GNU tar and BSD tar. Jun 20, 2016 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...) Aug 13, 2016 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, 2018 at 12:13
  • 5
    This is the right answer!
    – geckos
    Jun 12, 2019 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.