tar cvf /var/lib/backup/sample.tar /home/user/.project

However, when I extract, I get its parents as well

  - /home/
     - /user/
        - .project/

This tar commands does it job because it doesn't include anything else in its parents (other folders under user for example).

I want to do this programmatically, so changing the current working directory into /home/user/ is not really an option. Is it possible to do that?


You can either use the -C option to change into the /home/user directory before tarring or use --strip-components 2 on extraction.

tar cvfC /var/lib/backup/sample.tar /home/user .project
#                              Note the space ^
tar cvf /var/lib/backup/sample.tar /home/user/.project
tar Cxf /backup /var/lib/backup/sample.tar --strip-components 2
  • 1
    +1 cool .. I just found the -C switch when I was looking through the man page, but couldn't make sense of it .. sounded to me more like it would be used during untar. Learned something new. – Levon Jun 25 '12 at 2:00
  • @Kevin Thanks. The C option works flawlessly. Thank you! – User007 Jun 25 '12 at 2:01
  • 2
    I couldn't get it working like this. According reading gnu.org/software/tar/manual/tar.html#SEC118 I was successful with following form: tar cvf /var/lib/backup/sample.tar -C /home/user .project – Aivar Nov 1 '14 at 23:27

I think that if you cd to the toplevel directory that you want to create tar file of, you shouldn't have this problem. I.e.,

cd to user and the tar up .project .. you can specify the destination for the tar file in the /var/... as before.

Or is there a reason you don't want to/can't cd to user?

  • Yes. That would be one solution. Thanks. But I hope there is a better way? I want to deal wtih this programmatic ally, and I don't want to issue os.chdir(base_dir) in my code all the time :) so it would be nice if there's a way out of this. Thanks – User007 Jun 25 '12 at 1:49
  • @User007 Ah .. ok, I see. You may want to update your question to include that requirement. Nice user id by the way :) – Levon Jun 25 '12 at 1:52
  • Thanks. Yes. I've just updated my question. Oh it's to hide my identity... – User007 Jun 25 '12 at 1:56
  • 1
    @User007 love the 007 part .. and looks like you are working in Python too (which is another one of my favorites) – Levon Jun 25 '12 at 1:57
  • :) Yes. All right our friend Kevin helped me out with the right command. So I will give him the tick. But I upvoted you. Thanks! – User007 Jun 25 '12 at 2:01

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.